跳到主要内容

自定义服务器

Next.js 默认包含自己的带有 next start 的服务器。如果你有现有后端,你仍然可以将其与 Next.js 一起使用(这不是自定义服务器)。自定义 Next.js 服务器允许你以编程方式启动自定义模式的服务器。大多数情况下,你不需要这种方法。但是,如果你需要弹出,它是可用的。

¥Next.js includes its own server with next start by default. If you have an existing backend, you can still use it with Next.js (this is not a custom server). A custom Next.js server allows you to programmatically start a server for custom patterns. The majority of the time, you will not need this approach. However, it's available if you need to eject.

很高兴知道:

¥Good to know:

  • 在决定使用自定义服务器之前,请记住,只有当 Next.js 的集成路由无法满足你的应用要求时才应使用它。自定义服务器将删除重要的性能优化,例如 自动静态优化

    ¥Before deciding to use a custom server, keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like Automatic Static Optimization.

  • 无法在 Vercel 上部署自定义服务器。

    ¥A custom server cannot be deployed on Vercel.

  • 使用独立输出模式时,它不会跟踪自定义服务器文件。此模式会输出单独的最小 server.js 文件。这些不能一起使用。

    ¥When using standalone output mode, it does not trace custom server files. This mode outputs a separate minimal server.js file, instead. These cannot be used together.

查看自定义服务器的 以下示例

¥Take a look at the following example of a custom server:

import { createServer } from 'http'
import { parse } from 'url'
import next from 'next'

const port = parseInt(process.env.PORT || '3000', 10)
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url!, true)
handle(req, res, parsedUrl)
}).listen(port)

console.log(
`> Server listening at http://localhost:${port} as ${
dev ? 'development' : process.env.NODE_ENV
}`
)
})
import { createServer } from 'http'
import { parse } from 'url'
import next from 'next'

const port = parseInt(process.env.PORT || '3000', 10)
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
handle(req, res, parsedUrl)
}).listen(port)

console.log(
`> Server listening at http://localhost:${port} as ${
dev ? 'development' : process.env.NODE_ENV
}`
)
})

server.js 不通过 Next.js 编译器或打包过程运行。确保此文件所需的语法和源代码与你当前使用的 Node.js 版本兼容。查看示例

¥server.js does not run through the Next.js Compiler or bundling process. Make sure the syntax and source code this file requires are compatible with the current Node.js version you are using. View an example.

要运行自定义服务器,你需要像这样更新 package.json 中的 scripts

¥To run the custom server, you'll need to update the scripts in package.json like so:

{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}

或者,你可以设置 nodemonexample)。自定义服务器使用以下导入将服务器与 Next.js 应用连接:

¥Alternatively, you can set up nodemon (example). The custom server uses the following import to connect the server with the Next.js application:

import next from 'next'

const app = next({})

上面的 next import 是一个接收对象的函数,具有以下选项:

¥The above next import is a function that receives an object with the following options:

选项类型描述
confObject你将在 next.config.js 中使用相同的对象。默认为 {}
devBoolean(可选的)是否在开发模式下启动 Next.js。默认为 false
dirString(可选的)Next.js 项目的位置。默认为 '.'
quietBoolean(可选的)隐藏包含服务器信息的错误消息。默认为 false
hostnameString(可选的)服务器运行的主机名
portNumber(可选的)服务器运行的端口
httpServernode:http#Server(可选的)Next.js 在后面运行的 HTTP 服务器
turboBoolean(可选的)启用 Turbopack

然后可以使用返回的 app 让 Next.js 根据需要处理请求。

¥The returned app can then be used to let Next.js handle requests as required.