Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js ERR_HTTP_HEADERS_SENT: headers already sent

The response was sent twice: a missing return, a late async callback, or an error handler writing after a partial response. Send exactly once.

~4 min readNode.js
#Node.js#HTTP#Express#Troubleshooting
A Node response socket with two write arrows hitting one cyan gate, an amber headers plate beside it

Introduction & Quick Summary

text
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (node:_http_outgoing:659:11) at ServerResponse.header (node_modules/express/lib/response.js:795:10) at ServerResponse.json (node_modules/express/lib/response.js:267:15) at /app/routes/orders.js:41:21

The response has already been flushed to the socket and something tried to write again. Node keeps the header block immutable once it is on the wire, so any second res.set, res.status, res.json, res.end or res.writeHead after the first send throws this error. Your code sent a response twice.

The three shapes that cause almost all of them:

  • A missing return in a validation branch, so the success path also runs.
  • A late async callback — a timer, a promise, or an error handler that fires after the response is finished.
  • Two layers answering the same request — middleware that responds and calls next(), or an error handler that responds to an already-sent response.

The fix is structural, not a matter of adding if (!res.headersSent) everywhere: each request should have exactly one place that finishes the response.

CauseTypical lineFix
Missing return after res.jsonres.status(400).json(...)return res.status(400).json(...)
Async callback after sendsetTimeout(() => res.json(...))Respond once, ignore later callbacks
Error handler after partial writecatch (e) { res.status(500)... }if (res.headersSent) return next(e)
Middleware sends and continuesres.send(); next();Return, or don't respond
Double res.end on a streamstream.on("end", () => res.end())res.end() once, or pipeline
Framework + manual writeres.writeHead(...) then res.jsonPick one response API

Core Mechanics, Signatures & Reproducible Setup

A Node ServerResponse has three states: headers not sent, headers sent, finished. res.headersSent is true from the moment the status line and headers are flushed, which happens on the first write(), end(), or an explicit writeHead(). After that, setHeader throws ERR_HTTP_HEADERS_SENT. A second end() does not throw, but a second write() after end() does (ERR_STREAM_WRITE_AFTER_END).

Express helpers map onto that state machine: res.status() calls setHeader-adjacent internals, res.json() sets Content-Type and calls res.end(), and res.sendFile() streams. Any of them after the response started is this error.

A reproducible Express app:

js
// server.js import express from "express"; const app = express(); app.get("/orders/:id", async (req, res) => { const order = await db.order.find(req.params.id); if (!order) { res.status(404).json({ error: "not found" }); // no return } res.json(order); // second send }); app.listen(3000);
curl -i http://localhost:3000/orders/missing # HTTP/1.1 404 Not Found # Error [ERR_HTTP_HEADERS_SENT] ... (server log, connection still closes)

The client sees the first response and a correct-looking status; the error appears only in the server log. It is a logging noise bug until the second write lands on a socket someone is still reading.

The one-response helper that removes the class of bug:

js
function sendOnce(res, status, body) { if (res.headersSent || res.writableEnded) return false; res.status(status).json(body); return true; }

res.writableEnded is the companion check: headersSent is false until the first flush, but writableEnded flips when end() was called even if nothing was flushed yet.

Key Comparison Table

GuardTrue whenUse for
res.headersSentHeaders flushed to the socketPreventing a second status/header write
res.writableEndedend() has been calledPreventing a second body write
res.finishedDeprecated alias of writableEndedLegacy code only
req.aborted / req.destroyedClient went awaySkipping work for a gone client
res.socket.destroyedConnection closedVery late callbacks
LayerCorrect behaviorSymptom when wrong
Route handlerOne response per requestThis error on the second branch
MiddlewareEither respond or next(), never bothError after next() reaches a handler
Error middlewareDelegate if headers sentThis error inside catch
StreamLet pipeline end the responsewrite after end
Timeout guardCheck before sendingLate 504 after 200

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: The missing return

js
app.post("/users", async (req, res) => { if (!req.body.email) { res.status(422).json({ error: "email required" }); } const user = await db.user.create({ data: req.body }); res.status(201).json(user); });

Two sends. Every early exit needs return:

js
app.post("/users", async (req, res) => { if (!req.body.email) { return res.status(422).json({ error: "email required" }); } const user = await db.user.create({ data: req.body }); return res.status(201).json(user); });

An ESLint rule helps: consistent-return or the node/no-callback-literal family will not catch it, but @typescript-eslint/no-floating-promises plus an explicit return style does.

Case 2: Async work that outlives the response

js
app.get("/report", async (req, res) => { const timeout = setTimeout(() => { res.status(504).json({ error: "slow" }); // fires after success }, 10_000); const report = await buildReport(); clearTimeout(timeout); res.json(report); });

clearTimeout covers the normal path, but not the path where buildReport throws after the timeout already answered. Guard on both ends and keep the timer from writing at all:

js
let done = false; const timeout = setTimeout(() => { if (done) return; done = true; res.status(504).json({ error: "slow" }); }, 10_000); try { const report = await buildReport(); if (done) return; done = true; clearTimeout(timeout); res.json(report); } catch (err) { if (done) return; done = true; clearTimeout(timeout); res.status(500).json({ error: "failed" }); }

Case 3: Express error middleware

js
app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); // throws if already sent });

A route that streamed half a file and then threw leaves the response open but started; a JSON body appended to it corrupts the response. Delegate to the default handler, which closes the connection:

js
app.use((err, req, res, next) => { if (res.headersSent) return next(err); res.status(err.status || 500).json({ error: err.message }); });

Express's documentation calls this out explicitly; it is the single most useful guard in an Express app.

Case 4: Streams and downloads

js
app.get("/export", (req, res) => { const stream = createExport(); stream.pipe(res); stream.on("error", () => res.status(500).end()); // headers already sent });

By the time the error fires, pipe has written something. Use pipeline, which destroys both ends and reports one error:

js
import { pipeline } from "node:stream/promises"; app.get("/export", async (req, res) => { try { await pipeline(createExport(), res); } catch (err) { if (!res.headersSent) res.status(500).end(); else res.destroy(err); } });

Once bytes are on the wire you cannot change the status; the only honest options are to end the body or destroy the socket so the client sees an incomplete transfer.

Case 5: Middleware that responds and continues

js
function requireAuth(req, res, next) { if (!req.user) res.status(401).json({ error: "unauthorized" }); next(); // runs the route anyway }

Always return after responding in middleware:

js
function requireAuth(req, res, next) { if (!req.user) return res.status(401).json({ error: "unauthorized" }); next(); }

The same bug in TypeScript is easier to catch: annotate middleware as returning void | Promise<void> and enable noImplicitReturns, which flags the branch that returns nothing on one path and a value on another.

Case 6: Manual writeHead mixed with framework helpers

js
res.writeHead(200, { "Content-Type": "application/json" }); res.set("X-Request-Id", id); // ERR_HTTP_HEADERS_SENT res.end(JSON.stringify(data));

writeHead flushes everything, so later set calls fail. Set every header before the first write:

js
res.set("X-Request-Id", id); res.type("application/json"); res.status(200).send(JSON.stringify(data));

Common Compilation/Runtime Mistakes & Version Gotchas

  • Relying on try/catch around res.json. The error thrown by a second send lands in your own handler and can cascade into a third send. Treat it as a code defect, not a recoverable runtime error.
  • Express 5 async handlers. Rejected promises now reach the error middleware automatically, so a catch block that responds and rethrows produces the double send that Express 4 hid.
  • res.sendStatus() then res.json(). sendStatus ends the response with a text body; the follow-up JSON is the second send.
  • Compression and CORS middleware. compression and cors set headers; if a handler flushed early, their setHeader call is what throws, and the stack points at the middleware instead of your route.
  • Multiple response calls behind a retry. A for loop that retries a request and responds inside the loop sends once per attempt.
  • Node's error class. ERR_HTTP_HEADERS_SENT has code set, so err.code === "ERR_HTTP_HEADERS_SENT" is the reliable check in a global handler; the message text differs slightly between Node versions.

When a request returns an unexpected status, replay it with the curl builder and check the code against the HTTP status reference; a 404 followed by a logged 500 is the signature of this bug.

Primary references: response.writeHead() documents when headers become immutable, and Express's Error Handling guide specifies the headersSent delegation pattern.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.