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.

Introduction & Quick Summary
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:21The 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
returnin 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.
| Cause | Typical line | Fix |
|---|---|---|
Missing return after res.json | res.status(400).json(...) | return res.status(400).json(...) |
| Async callback after send | setTimeout(() => res.json(...)) | Respond once, ignore later callbacks |
| Error handler after partial write | catch (e) { res.status(500)... } | if (res.headersSent) return next(e) |
| Middleware sends and continues | res.send(); next(); | Return, or don't respond |
Double res.end on a stream | stream.on("end", () => res.end()) | res.end() once, or pipeline |
| Framework + manual write | res.writeHead(...) then res.json | Pick 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:
// 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:
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
| Guard | True when | Use for |
|---|---|---|
res.headersSent | Headers flushed to the socket | Preventing a second status/header write |
res.writableEnded | end() has been called | Preventing a second body write |
res.finished | Deprecated alias of writableEnded | Legacy code only |
req.aborted / req.destroyed | Client went away | Skipping work for a gone client |
res.socket.destroyed | Connection closed | Very late callbacks |
| Layer | Correct behavior | Symptom when wrong |
|---|---|---|
| Route handler | One response per request | This error on the second branch |
| Middleware | Either respond or next(), never both | Error after next() reaches a handler |
| Error middleware | Delegate if headers sent | This error inside catch |
| Stream | Let pipeline end the response | write after end |
| Timeout guard | Check before sending | Late 504 after 200 |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: The missing return
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:
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
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:
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
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:
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
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:
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
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:
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
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:
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/catcharoundres.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
catchblock that responds and rethrows produces the double send that Express 4 hid. res.sendStatus()thenres.json().sendStatusends the response with a text body; the follow-up JSON is the second send.- Compression and CORS middleware.
compressionandcorsset headers; if a handler flushed early, theirsetHeadercall is what throws, and the stack points at the middleware instead of your route. - Multiple response calls behind a retry. A
forloop that retries a request and responds inside the loop sends once per attempt. - Node's error class.
ERR_HTTP_HEADERS_SENThascodeset, soerr.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 documentationThe Node.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js: ERR_DLOPEN_FAILED invalid ELF header
Invalid ELF header means a native addon was built for another OS or architecture. Rebuild it inside the target image instead of copying node_modules.
Node.js ERR_INVALID_ARG_TYPE: the argument must be of type
ERR_INVALID_ARG_TYPE is Node's validator naming a wrong argument. Read the quoted argument, validate at the boundary and default env values.
ERR_MODULE_NOT_FOUND: Cannot find module imported from an ESM file
ESM resolves specifiers literally: extensions are required, directories do not resolve to index files, and exports maps block deep imports.
Node.js 26 upgrade: rmdir, native addons and removed flags
Three breaks stop a deploy: rmdir with recursive throws, the transform-types flag is gone, and the module ABI moved to 147.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.