Skip to main content

自定义服务器

Examples

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

¥By default, Next.js includes its own server with next start. 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 start a server 100% programmatically in order to use custom server patterns. Most of the time, you will not need this - but it's available for complete customization.

很高兴知道:

¥Good to know:

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

    ¥Before deciding to use a custom server, please 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 serverless functions and Automatic Static Optimization.

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

    ¥A custom server cannot be deployed on Vercel.

  • 独立输出模式,不跟踪自定义服务器文件,此模式输出一个单独的最小 server.js 文件。

    ¥Standalone output mode, does not trace custom server files and this mode outputs a separate minimal server.js file instead.

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

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

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = 3000
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()

app.prepare().then(() => {
createServer(async (req, res) => {
try {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl

if (pathname === '/a') {
await app.render(req, res, '/a', query)
} else if (pathname === '/b') {
await app.render(req, res, '/b', query)
} else {
await handle(req, res, parsedUrl)
}
} catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('internal server error')
}
})
.once('error', (err) => {
console.error(err)
process.exit(1)
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`)
})
})

server.js 不通过 babel 或 webpack。确保此文件所需的语法和源与你正在运行的当前节点版本兼容。

¥server.js doesn't go through babel or webpack. Make sure the syntax and sources this file requires are compatible with the current node version you are running.

要运行自定义服务器,你需要更新 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"
}
}

自定义服务器使用以下导入将服务器与 Next.js 应用连接:

¥The custom server uses the following import to connect the server with the Next.js application:

const next = require('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 中使用相同的对象。默认为 {}
customServerBoolean(可选的)当 Next.js 创建服务器时设置为 false
devBoolean(可选的)是否在开发模式下启动 Next.js。默认为 false
dirString(可选的)Next.js 项目的位置。默认为 '.'
quietBoolean(可选的)隐藏包含服务器信息的错误消息。默认为 false
hostnameString(可选的)服务器运行的主机名
portNumber(可选的)服务器运行的端口
httpServernode:http#Server(可选的)Next.js 在后面运行的 HTTP 服务器

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

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

禁用文件系统路由

¥Disabling file-system routing

默认情况下,Next 将在与文件名匹配的路径名下提供 pages 文件夹中的每个文件。如果你的项目使用自定义服务器,此行为可能会导致从多个路径提供相同的内容,这可能会带来 SEO 和 UX 问题。

¥By default, Next will serve each file in the pages folder under a pathname matching the filename. If your project uses a custom server, this behavior may result in the same content being served from multiple paths, which can present problems with SEO and UX.

要禁用此行为并防止基于 pages 中的文件进行路由,请打开 next.config.js 并禁用 useFileSystemPublicRoutes 配置:

¥To disable this behavior and prevent routing based on files in pages, open next.config.js and disable the useFileSystemPublicRoutes config:

module.exports = {
useFileSystemPublicRoutes: false,
}

请注意,useFileSystemPublicRoutes 禁用来自 SSR 的文件名路由;客户端路由仍然可以访问这些路径。使用此选项时,你应该防止以编程方式导航到你不想要的路由。

¥Note that useFileSystemPublicRoutes disables filename routes from SSR; client-side routing may still access those paths. When using this option, you should guard against navigation to routes you do not want programmatically.

你可能还希望配置客户端路由以禁止客户端重定向到文件名路由;请参阅 router.beforePopState

¥You may also wish to configure the client-side router to disallow client-side redirects to filename routes; for that refer to router.beforePopState.