网页
综合
更新时间 2025-04-24 00:00:00
How to set up a custom server in Next.js
自动蜘蛛
nextjs.org
正文约 2355 字
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.
Take a look at the following example of a custom server:
Set your own response headers before calling handle: Next.js begins sending the response inside handle(req, res), so by the time its promise resolves res.headersSent is already true and any later res.setHeader() call is silently discarded. Set headers you own, such as Set-Cookie, before handing the request to Next.js:
The same ordering applies when wrapping Next.js in another framework, for example reply.raw in Fastify or res in Express.
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.
To run the custom server, you'll need to update the scripts in package.json like so:
Alternatively, you can set up nodemon (example). The custom server uses the following import to connect the server with the Next.js application:
The above next import is a function that receives an object with the following options:
The returned app can then be used to let Next.js handle requests as required.
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.
To disable this behavior and prevent routing based on files in pages, open next.config.js and disable the useFileSystemPublicRoutes config:
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.
You may also wish to configure the client-side router to disallow client-side redirects to filename routes; for that refer to router.beforePopState.
Last updated April 24, 2025
Subscribe to our newsletter
Stay updated on new releases and features, guides, and case studies.
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。