Fixing ERR_HTTP_HEADERS_SENT in Node.js
ERR_HTTP_HEADERS_SENT in Node.js is raised when you try to write headers again for a request after the response has already been sent. In my tests, the error appeared in two cases: a missing return after sending an error response, and sending the real result after a timeout response had already gone out. The error goes away if you end the handler right after sending a response, or check res.headersSent to see whether a response has already been sent.
The error shows up when you add input validation or timeout handling to an API server built with the Node.js http module or Express, and that leaves two places that can send a response. I reproduced this error in a test environment and included the messages exactly as they were printed. I also confirmed that the error stops after the fix.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Express 5.3.0. I sent the requests with curl. I replaced the working directory path in the output with /path/to/app. I left out response headers that change on every request, such as Date, and headers unrelated to this issue, such as Content-Length. The output shows only the HTTP/1.1 … status line and Content-Type. I did not test Express 4 or other frameworks such as Fastify.
What the error means
ERR_HTTP_HEADERS_SENT in the Node.js error list means you tried to add headers after they had already been sent. Calling writeHead() or setHeader() after the headers are sent raises this error. The response.writeHead() documentation also says it should be called only once per response, before response.end().
The message depends on which method you called after the headers were sent. In my tests, calling writeHead() produced Cannot write headers after they are sent to the client. Calling setHeader() produced Cannot set headers after they are sent to the client. Express's res.send() and res.json() call setHeader() internally, so you see the second message when using them.
Cause 1: Forgetting return after sending an error response
The following missing-return.mjs is a server built only with the Node.js http module. If the query parameter name is missing, it sends a 400 response, but it forgets the return after that.
// Sends 400 when input is missing, but the return is forgotten
import http from 'node:http';
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
const name = url.searchParams.get('name');
if (!name) {
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('name がありません\n');
}
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`こんにちは、${name}さん\n`);
});
server.listen(3000, () => console.log('listening on 3000'));
I sent three requests in this order: one with name, one without, and one with name again.
$ curl -s -i 'http://localhost:3000/?name=neko'
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
こんにちは、nekoさん
$ curl -s -i 'http://localhost:3000/'
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
name がありません
$ curl -s -i 'http://localhost:3000/?name=neko'
The second request got the correct 400 response. However, while handling that request, the server raised the following error and exited with exit code 1. As a result, the third request could not connect, and curl ended with exit code 7 (could not connect to the server) without receiving anything.
listening on 3000
node:_http_server:354
throw new ERR_HTTP_HEADERS_SENT('write');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot write headers after they are sent to the client
at ServerResponse.writeHead (node:_http_server:354:11)
at Server.<anonymous> (file:///path/to/app/missing-return.mjs:11:7)
at Server.emit (node:events:519:28)
at parserOnIncoming (node:_http_server:1186:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:125:17) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Node.js v22.23.4
The second at line, missing-return.mjs:11:7, points to the line where the second writeHead() was called. After sending the 400 response inside the if block, execution continued, and line 11 tried to write the 200 headers and failed. Start with that line, then look for where the response was sent earlier.
The fix is to return right after sending the response, so the function ends there.
if (!name) {
res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('name がありません\n');
return;
}
When I sent the same three requests again, the third one returned 200 OK with こんにちは、nekoさん. The server output was only listening on 3000, and the error no longer appeared.
With Express, the server does not stop; the error only appears in the log
Here is the same mistake written in Express 5.
// Express 5: sends 400 when input is missing, but the return is forgotten
import express from 'express';
const app = express();
app.get('/hello', (req, res) => {
if (!req.query.name) {
res.status(400).send('name がありません');
}
res.send(`こんにちは、${req.query.name}さん`);
});
app.listen(3000, () => console.log('listening on 3000'));
I sent /hello?name=neko, /hello, and /hello?name=neko in that order. curl received the correct response each time (200, 400, 200), and the server kept running. However, the server log showed the following error.
listening on 3000
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (node:_http_outgoing:700:11)
at ServerResponse.header (/path/to/app/node_modules/express/lib/response.js:685:10)
at ServerResponse.send (/path/to/app/node_modules/express/lib/response.js:141:14)
at file:///path/to/app/express-missing-return.mjs:10:7
at Layer.handleRequest (/path/to/app/node_modules/router/lib/layer.js:152:17)
at next (/path/to/app/node_modules/router/lib/route.js:157:13)
at Route.dispatch (/path/to/app/node_modules/router/lib/route.js:117:3)
at handle (/path/to/app/node_modules/router/index.js:435:11)
at Layer.handleRequest (/path/to/app/node_modules/router/lib/layer.js:152:17)
at /path/to/app/node_modules/router/index.js:295:15 {
code: 'ERR_HTTP_HEADERS_SENT'
}
Unlike the http module case, the server did not stop. This is because Express catches exceptions thrown synchronously inside route handlers, as described in Express's error handling guide. For that reason, curl and the browser show no visible problem, and you only notice the error if you check the log.
In the stack trace, skip the lines inside node_modules and find the line in your own file. Here it is express-missing-return.mjs:10:7, which is where the second res.send() was called.
In Express too, the fix is to add return. You can write it on one line as return res.status(400).send(...).
app.get('/hello', (req, res) => {
if (!req.query.name) {
return res.status(400).send('name がありません');
}
res.send(`こんにちは、${req.query.name}さん`);
});
When I sent the same three requests again, the responses were unchanged, and the error no longer appeared in the log.
Cause 2: Sending the real result after a timeout response has been sent
Even with return in place, the error can still occur if you add your own timeout handling. The following express-timeout.mjs sends a 503 response with a "timeout" error message after one second. However, when the data loading finishes (here a function that just waits 1.5 seconds stands in for it), it still tries to send the result with res.json().
// Express 5: returns a timeout response after 1 second, but still tries to send a response after the slow work finishes
import express from 'express';
const app = express();
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
async function loadReport() {
await wait(1500); // stand-in for a slow database
return { total: 42 };
}
app.get('/report', async (req, res) => {
setTimeout(() => {
res.status(503).json({ error: '時間切れです' });
}, 1000);
const report = await loadReport();
res.json(report);
});
app.listen(3000, () => console.log('listening on 3000'));
curl received the 503 response. After that, the server log showed the following error.
$ curl -s -i 'http://localhost:3000/report'
HTTP/1.1 503 Service Unavailable
Content-Type: application/json; charset=utf-8
{"error":"時間切れです"}
listening on 3000
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (node:_http_outgoing:700:11)
at ServerResponse.header (/path/to/app/node_modules/express/lib/response.js:685:10)
at ServerResponse.send (/path/to/app/node_modules/express/lib/response.js:141:14)
at ServerResponse.json (/path/to/app/node_modules/express/lib/response.js:249:15)
at file:///path/to/app/express-timeout.mjs:17:7 {
code: 'ERR_HTTP_HEADERS_SENT'
}
Line 17 is res.json(report) after the loading finished. By then, the timer had already sent the 503 response. Because the handler is async, the exception thrown by res.json() was passed to Express as a rejected Promise, and it appeared in the log. The same guide also says that Express 5 passes failures from route handlers that return a Promise to next().
When two places can send a response and the timing decides which one runs first, a return alone does not fix it. Before sending a response, check whether one has already been sent by using res.headersSent. headersSent is a read-only value that becomes true once the headers have been sent.
async function loadReport(ms) {
await wait(ms); // stand-in for a slow database
return { total: 42 };
}
app.get('/report', async (req, res) => {
const timer = setTimeout(() => {
res.status(503).json({ error: '時間切れです' });
}, 1000);
const report = await loadReport(Number(req.query.ms ?? 1500));
clearTimeout(timer);
if (res.headersSent) {
console.log('時間切れの応答を返したあとなので、結果は返さない');
return;
}
res.json(report);
});
When loading finishes first, clearTimeout() stops the timer so the timeout response is never sent. To test both paths, I made loadReport() accept a wait time and let the query parameter ms set it.
$ curl -s -i 'http://localhost:3000/report'
HTTP/1.1 503 Service Unavailable
Content-Type: application/json; charset=utf-8
{"error":"時間切れです"}
$ curl -s -i 'http://localhost:3000/report?ms=200'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"total":42}
When loading took 1.5 seconds, the 503 response was returned. The log showed 時間切れの応答を返したあとなので、結果は返さない and no error. When loading finished in 0.2 seconds, the real result {"total":42} was returned.
You can use the same check in your own error-handling middleware. The Express guide says that if an error is passed to next() after the response has started, Express's default error handler closes the connection. The guide shows an example where custom error-handling middleware checks res.headersSent, and if it is true, skips sending its own response and calls return next(err) to let the default error handler take over.




