Unverified Commit 30e73d2d authored by Joseph's avatar Joseph Committed by GitHub

docs: note that response headers must be set before calling handle() in a custom server (#97693)

Fixes: #82387

A custom server that calls `res.setHeader()` after `await handle(req,
res)` silently loses the header, because Next.js has already begun
sending the response by the time `handle` resolves. Unlike a normal Node
`setHeader()` after `headersSent`, this does not throw, so the header
just never reaches the client. This adds a note to the custom server
guide showing the correct ordering and pointing out that the same
applies to framework wrappers such as `reply.raw` in Fastify.
parent 88483bde
...@@ -59,6 +59,16 @@ app.prepare().then(() => { ...@@ -59,6 +59,16 @@ app.prepare().then(() => {
}) })
``` ```
> **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:
>
> ```js
> res.setHeader('Set-Cookie', 'sessionId=abc123; Max-Age=2592000')
>
> await handle(req, res)
> ```
>
> 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](https://github.com/vercel/next.js/tree/canary/examples/custom-server). > `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](https://github.com/vercel/next.js/tree/canary/examples/custom-server).
To run the custom server, you'll need to update the `scripts` in `package.json` like so: To run the custom server, you'll need to update the `scripts` in `package.json` like so:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment