Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Hi Scott @Hendrixer
When I fetch one note in /pages/notes/[id].js the app crashes with the follwoing error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:536:11)
at DevServer.sendHTML (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/server/next-dev-server.js:31:5)
at DevServer.render (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:56:37)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Object.fn (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:32:107)
at async Router.execute (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/router.js:38:67)
at async DevServer.run (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:49:494)
at async DevServer.handleRequest (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:18:101) {
code: 'ERR_HTTP_HEADERS_SENT'
}
events.js:291
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at writeAfterEnd (_http_outgoing.js:646:15)
at ServerResponse.end (_http_outgoing.js:766:7)
at ServerResponse.end (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/compiled/compression/index.js:1:148805)
at DevServer.handleRequest (/Users/jus/CODE/Courses/FrontEndMasters/Workshops/nextjs-themeui/node_modules/next/dist/next-server/server/next-server.js:18:189)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:705:7)
at processTicksAndRejections (internal/process/task_queues.js:81:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
This is my code for /pages/notes/[id].js:
/** @jsx jsx */
import { jsx } from 'theme-ui';
import { useRouter } from 'next/router';
import Link from 'next/link';
const DynamicPage = ({ note }) => {
return (
<div sx={{ variant: 'containers.page' }}>
<h1>Note: {note.title} </h1>
</div>
);
};
export default DynamicPage;
export async function getServerSideProps({ params, req, res }) {
const response = await fetch(`http://localhost:3000/api/notes/${params.id}`);
// so much power!
if (!response.ok) {
res.writeHead(302, { Location: '/notes' });
res.end();
return { props: {} };
}
const { data } = await response.json();
if (data) {
return {
props: { note: data },
};
}
}
NOTE: only difference I have from your repo is named exports, my API is at API/notes & my components and data are in root.
A console.log(response) shows:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kTransformState)]: [Object]
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'http://localhost:3000/api/notes/1596709251707',
status: 404,
statusText: 'Not Found',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
Steps to trigger the error - follow this path:
- yarn dev -- OK
- go to localhost:3000 -- OK
- click Notes in Nav bar -- OK
- click any Note -- error (status 404 - not found)
Steps to avoid error:
- yarn dev -- OK
- go to localhost: 3000 -- OK
- go to http://localhost:3000/api/notes/{id from step 4 above} But as soon as you click Notes in Nav bar then you're in trouble again.
Looks like new IDs are generated and somehow headers cannot be updated anymore.
I am getting this error too. I was able to fix it by adding `typeof window === 'undefined' to the conditional expression with writeHead. Now it looks like this:
if (!response.ok && typeof window === 'undefined') {
res.writeHead(302, { Location: '/notes' })
res.end()
return {props: {}}
}
I am honestly now positive why you need this though. @juicecultus
Instead of strict equality (===) operator use Object,is() and le me know!
I had a similar issue, but I was trying to do all with ts. When I convert all to js everything was working as should be
Can anyone explain what exactly is happening here? This seems to cover intricacies of next.js and server responses.
Having the same error. However, if I log params as the first line of getServerSideProps, the function works. Some kind of timing issue where params is not ready when fetch tries to call it, maybe?
export async function getServerSideProps({params, req, res}) {
console.log(params)
const response = await fetch(`http://localhost:3000/api/note/${params.id}`)
if (!response.ok) {
res.writeHead(302, { Location: '/notes' })
res.end()
return {props: {}}
}
const {data} = await response.json()
if (data) {
return {
props: {note: data}
}
}
}```
try this it worked for me
export async function getServerSideProps({ params, req, res }) {
const response = await fetch(http://localhost:3000/api/note/${params.id});
if (!response.ok) { return res.writeHead(302, { Location: "/notes" }).end(); }
const { data } = await response.json();
if (data) { return { props: { note: data }, }; } }