ERR_HTTP_HEADERS_SENT
Node.jsERRORNotableHTTPHIGH confidence

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.

What this means

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.

Why it happens
  1. 1Calling `res.setHeader()`, `res.statusCode =`, or `res.writeHead()` after `res.write()` or `res.end()` has been called.
  2. 2Calling a response-sending method multiple times in the same asynchronous callback or code path.
  3. 3An error-handling middleware attempts to set headers after a previous middleware has already sent a response.
How to reproduce

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.

trigger — this will error
trigger — this will error
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.

Set All Headers Before Sending Body
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.

Check if Headers are Already 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.

Code examples
Triggerjs
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_SENT
Handle in try/catchjs
try {
  // 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
  }
}
Defensive pattern to avoid itjs
function respond(res, status, body) {
  if (res.headersSent) return  // guard — headers already sent
  res.writeHead(status)
  res.end(body)
}
What not to do

Sources
Official documentation ↗

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

← All Node.js errors