skip to content

In Node.js node:http, how do res.setHeader and res.writeHead differ, and what causes the ERR_HTTP_HEADERS_SENT error?

level: middleimportance: must knowfreq 64%

answer

  1. staged versus sent
  2. implicit headers on first write
  3. writeHead wins a merge
  4. headersSent flips once rendered
  5. a second response path

basics

~20 s

res.setHeader stages one header that Node sends with the first write; res.writeHead sends the status and headers at once and wins over staged ones. Once headers are rendered, any further setHeader or writeHead throws ERR_HTTP_HEADERS_SENT.

solid answer

~40 s

`res.setHeader(name, value)` stores a header in the response's mutable header list; you can read it back with `getHeader` or remove it until headers go out. That is Node's **implicit header** mode: the first `res.write()` or `res.end()` renders the stored headers with `res.statusCode`. `res.writeHead(status, headers)` renders the head explicitly, merging in anything set with `setHeader`, with `writeHead`'s values taking precedence; it may be called once, before `end()`. After either path, `res.headersSent` is `true`, and `setHeader`, `appendHeader`, `removeHeader` or a second `writeHead` throws `ERR_HTTP_HEADERS_SENT` ("Cannot set headers after they are sent to the client"). The usual cause is code that responds twice: a callback and a fallthrough, or a `catch` writing an error after a success response.

code

javascript · 13 lines
javascript
import { createServer } from 'node:http';

createServer((req, res) => {
  res.setHeader('Content-Type', 'text/plain');
  res.write('partial ');            // implicit headers are rendered here
  console.log(res.headersSent);     // true
  try {
    res.setHeader('X-Late', '1');   // too late
  } catch (err) {
    console.log(err.code);          // ERR_HTTP_HEADERS_SENT
  }
  res.end('done');
}).listen(3000);

go deeper

for a junior

Know that setHeader stages headers, writeHead sends status and headers together, and that changing headers after the first write throws ERR_HTTP_HEADERS_SENT.

for a middle

Explain implicit header mode, the merge rule where writeHead wins, and why headersSent turns true at the first write rather than when bytes leave.

for a senior

Trace ERR_HTTP_HEADERS_SENT to the double-response path that caused it, and design error handling that checks headersSent before trying to change a status.

for a principal

Set a team convention for handlers: return after responding, one error path that respects headersSent, and streamed responses only where losing the status code is acceptable.

## Two ways to produce the response head An HTTP response starts with a status line and headers, and a `ServerResponse` can render that head in two ways. - **Implicit headers.** You set `res.statusCode` and call `res.setHeader(name, value)` as many times as you like. Nothing goes out yet. The first `res.write()` or `res.end()` makes Node call `writeHead(res.statusCode)` internally and render whatever is staged. - **Explicit headers.** `res.writeHead(statusCode[, statusMessage][, headers])` renders the head in one call. It returns `res`, so `res.writeHead(200, {...}).end(body)` chains. | | `res.setHeader` | `res.writeHead` | |---|---|---| | What it does | stages one header | renders status and headers | | How often | any number of times before headers go out | once per response | | Readable back with `getHeader` | yes | only headers that were staged with `setHeader` | | On conflict | loses | its values take precedence | | After headers are sent | throws `ERR_HTTP_HEADERS_SENT` | throws `ERR_HTTP_HEADERS_SENT` | The http docs give the merge rule with an example: after `setHeader('Content-Type', 'text/html')` and `writeHead(200, { 'Content-Type': 'text/plain' })` the response carries `text/plain`. They also note that when `writeHead` is used without any `setHeader`, the headers are written directly without being cached, so `getHeader` will not return them. That matters for code further down the chain, such as logging that reads headers back. ## What "sent" means to Node `res.headersSent` becomes `true` when Node has **rendered** the head into its outgoing buffer, not necessarily when bytes reach the network. That happens on the explicit `writeHead`, or on the first `write`/`end` in implicit mode. From then on the head is fixed: - `res.setHeader`, `res.appendHeader` and `res.removeHeader` throw `ERR_HTTP_HEADERS_SENT` with the message "Cannot set headers after they are sent to the client" (the verb changes to append or remove for those methods); - a second `res.writeHead` throws the same code with "Cannot write headers after they are sent to the client". The error is synchronous and thrown, so inside a request handler it either reaches your `try`/`catch` or becomes an uncaught exception. ## Where the error really comes from The error message points at a header, but the bug is almost always **two code paths both responding**: 1. A callback-style operation responds in its callback, and the code after the call also responds. 2. A loop or `if` chain that lacks a `return` after the first response. 3. A `try` block that has already started a successful streamed response, and a `catch` that tries to `writeHead(500)` when a later step fails. 4. A timer or event listener that responds after the main path already did. Framework users meet the same message, because frameworks call these methods underneath; it is Node's error, not the framework's. ## Writing handlers that cannot double-respond - Return immediately after every response call, so no code runs after it. - In an error handler, check `res.headersSent` first. If headers are out you cannot change the status; the honest options are to end or destroy the response so the client sees a truncated body rather than a fake success. - Prefer `writeHead` when the status and headers are known together, and `setHeader` when several parts of the code contribute headers before the body starts. - Remember the order cost of streaming: once the first body chunk is written, late information such as a checksum or a final status can no longer go in a header. ## Reading where a response stands Three properties let a shared error path decide what is still possible: - `res.headersSent`: the head has been rendered, so status and headers are fixed; - `res.writableEnded`: `res.end()` has been called (the older `res.finished` is deprecated in its favour), although the data may not be flushed yet; - `res.writableFinished`: all data has been flushed to the underlying system, just before `'finish'` fires. Checking them in that order tells the error path whether it can still set a status, can still write, or should only log. ## Related response checks Two neighbouring checks are easy to confuse with this one. A header name or value with invalid characters throws a `TypeError` immediately, whatever the timing. And when `res.strictContentLength` is set to `true` (it defaults to `false`), Node compares the `Content-Length` you declared with the bytes you wrote and throws `ERR_HTTP_CONTENT_LENGTH_MISMATCH` when they differ. Neither is about timing; `ERR_HTTP_HEADERS_SENT` always is.

  • A handler has already streamed half of a large response when a downstream read fails. What can it still tell the client?
    Nothing through the status line: `res.headersSent` is true and the 200 is already out. The handler should stop writing and destroy the response (`res.destroy(err)`), so the connection closes and the client sees an incomplete body rather than a clean end that looks like success. Logging the failure server-side is the only full record.
  • Why might res.getHeader('Content-Type') return undefined in logging code that runs after a handler called res.writeHead(200, { 'Content-Type': 'text/plain' })?
    When `writeHead` runs without any earlier `setHeader`, Node writes the supplied headers straight into the head without caching them in the mutable header list, so `getHeader` has nothing to return. Staging headers with `setHeader` before `writeHead` keeps them readable, which is what the docs recommend when code needs to inspect headers later.

  • Thinks headersSent means the bytes reached the client
  • Believes setHeader overrides a value passed to writeHead
  • Blames the header itself rather than a second response path
  • Expects to send a 500 after the body has started
  • Calls writeHead more than once to change the status
  • Thinks the error comes from Express rather than node:http