Cannot set headers after they are sent to the client.
Production Risk
Medium. This error indicates a server-side logic flaw. While it might not crash the server immediately, it means the client receives an incorrect or malformed response.
This error occurs in the HTTP module when you attempt to modify response headers (e.g., setting a status code or a header value) after the headers have already been sent to the client. Once the body of the response has started to be written, the headers are finalized and flushed. Any further attempts to change them are invalid and will result in this error.
- 1Calling `res.setHeader()`, `res.statusCode =`, or `res.writeHead()` after `res.write()` or `res.end()` has been called.
- 2Calling a response-sending method multiple times in the same asynchronous callback or code path.
- 3An error-handling middleware attempts to set headers after a previous middleware has already sent a response.
This error is thrown by the HTTP response object when a header-mutating method is called but the `headersSent` property of the response object is already true.
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain');
res.end('ok');
try {
res.setHeader('X-My-Header', '123'); // This will throw
} catch (err) {
console.error(err.message);
}
});
server.listen(3000);expected output
Cannot set headers after they are sent to the client
Fix 1
Set All Headers Before Sending Body
WHEN Defining an HTTP response handler.
const server = http.createServer((req, res) => {
// Set all headers first.
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.setHeader('X-Custom-Header', 'value');
// Then, send the body.
res.end(JSON.stringify({ message: 'success' }));
});Why this works
Organize your code to ensure that all header manipulations and status code settings are performed before the first call to `res.write()` or `res.end()`.
Fix 2
Check if Headers are Already Sent
WHEN In complex logic or middleware where the response might have already been sent.
function myMiddleware(req, res, next) {
if (!res.headersSent) {
res.setHeader('X-Powered-By', 'Unicorns');
}
next();
}Why this works
Use the `res.headersSent` boolean property to check if it is still safe to modify headers before attempting to do so. This prevents errors in code paths where the response state is uncertain.
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain');
res.end('ok');
try { // this triggers ERR_HTTP_HEADERS_SENTtry {
// operation that may throw ERR_HTTP_HEADERS_SENT
riskyOperation()
} catch (err) {
if (err.code === 'ERR_HTTP_HEADERS_SENT') {
console.error('ERR_HTTP_HEADERS_SENT:', err.message)
} else {
throw err
}
}function respond(res, status, body) {
if (res.headersSent) return // guard — headers already sent
res.writeHead(status)
res.end(body)
}✕
https://github.com/nodejs/node/blob/main/lib/_http_server.js
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev