Express crashes with ERR_HTTP_HEADERS_SENT
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clientShort answer
This error means your code tried to write headers or a second response after Express already sent one. Read the stack trace to find the second send. The usual causes are a route that responds twice, an error handler that ignores res.headersSent, and next() called more than once.
Fix it fast
1Find out which cause you have
Read the first lines of the stack trace that are in your own files, not in node_modules. The line named there is the second attempt to respond, so look just above it for the first one.
node server.js 2>&1 | grep -A6 "ERR_HTTP_HEADERS_SENT"2Match what you see, then jump to its fix
- 1
The trace ends at a res.* call inside one of your route handlersA code path calls res.send, res.json or res.redirect twiceFix - 2
The error appears after a failure while streaming or after res.write, and the trace includes your error-handling middlewareA custom error handler writes to a response that has already startedFix - 3
The failure shows up on requests that hit an error, and the default handler is named in the tracenext(err) is called more than once, or after a response was sentFix
- 1
What does the error look like?
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clientError: Can't set headers after they are sent to the client
Cause 1 of 3
A code path calls res.send, res.json or res.redirect twice
1Check
Headers are sent with the first response call, and a response can only be started once. Look for a branch that answers and then falls through to another answer, or a callback that responds after the main code already did.
grep -n "res\.\(send\|json\|redirect\|end\|render\)" routes/users.js2Fix
Make each path end after it responds: put return in front of the res call inside branches, or use else.
app.get('/user/:id', async (req, res) => {
const user = await findUser(req.params.id);
if (!user) {
return res.status(404).json({ error: 'not found' });
}
res.json(user);
});3Verify
Request the route for both a found and a missing id; the server stays up.
curl -i http://localhost:3000/user/1
curl -i http://localhost:3000/user/999999Confirmed by nodejs.org
Cause 2 of 3
A custom error handler writes to a response that has already started
1Check
Once a response is partly written, Express cannot switch to an error page. A handler that always calls res.status(500) then fails with this very error.
grep -rn "(err, req, res, next)" --include=*.js .2Fix
At the top of every error handler, pass the error on when the headers are already out. The default handler then closes the connection.
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
res.status(500).json({ error: 'server error' });
});3Verify
Trigger an error halfway through a streamed response; the process logs it and keeps running.
curl -N http://localhost:3000/streamConfirmed by expressjs.com
Cause 3 of 3
next(err) is called more than once, or after a response was sent
1Check
A callback that calls next(err) and then carries on, or a promise chain with both .then and a catch that each reply, sends the error through the handler a second time.
grep -n "next(" middleware/*.js routes/*.js2Fix
Call next(err) once and return right after it. In async functions, let the error be thrown instead of calling next yourself; Express 5 forwards a rejected promise to the error handlers.
app.get('/report', async (req, res) => {
const data = await buildReport(); // a rejection goes to the error handler
res.json(data);
});3Verify
Force buildReport to fail; one error response is sent and the log shows one error.
curl -i http://localhost:3000/reportConfirmed by expressjs.com
How do I stop it coming back?
- Write return in front of every early res.* call so a branch cannot continue past its answer.
- Use async functions for handlers, and keep one error-handling middleware at the end that checks res.headersSent.
- Do not set headers after any await that could have sent a response in another branch; set them first.
- Add a test for each error branch of a route, not only the success case.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fixBack end
Browser blocks a stylesheet or script: MIME type mismatch with nosniff
The Network tab shows the asset URL answered with Content-Type text/html
With X-Content-Type-Options: nosniff the browser accepts a stylesheet only as text/css and a script only as a JavaScript type.
3 causes, each with a fix