Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent occurs in Express when your route handler or middleware attempts to send a second response (or set response headers/status) after HTTP headers have already been flushed to the client by an earlier res.json(), res.send(), res.redirect(), or res.end(). Fix it by returning early from branches after sending a response, ensuring middleware/async callbacks do not fall through after responding, and avoiding sending multiple responses on error.
1. Return Early After Sending a Response
The most common cause is forgetting return after an early validation or error response, allowing execution to continue and hit a second res.json() or res.send():
// Bad vs. Good: always return after sending a response in a branch
app.get("/users/:id", async (req, res, next) => {
try {
const userId = req.params.id;
if (!userId) {
return res.status(400).json({ error: "User ID is required" });
}
const user = await findUserById(userId);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
return res.status(200).json({ user });
} catch (err) {
if (res.headersSent) {
return next(err);
}
return next(err);
}
});
return res.status(...).json(...): Stops the rest of the current handler from running after the response is initiated.- Check
res.headersSent: If headers were already sent before a late error occurs, avoid callingres.status(...).json(...)again and delegate to Express error handling (next(err)).
2. Guard Middleware, Async Flow, and catch Blocks
Another frequent cause is calling next() after sending a response in middleware, or sending a response inside try and then sending another response inside catch when something inside try throws after headers were sent:
// Middleware & async route guard to prevent duplicate responses
function requireAuth(req, res, next) {
const token = req.headers.authorization;
if (!token) {
res.status(401).json({ error: "Unauthorized" });
return; // Do not call next() after sending a response
}
next();
}
app.post("/orders", requireAuth, async (req, res, next) => {
try {
const order = await createOrder(req.body);
return res.status(201).json({ order });
} catch (err) {
if (res.headersSent) {
return;
}
return res.status(500).json({ error: "Failed to create order" });
}
});
- Never call
next()after sending a response unless intentionally passing control to a downstream handler that has not responded yet. - Guard
catchblocks withif (res.headersSent) return;: Prevents a secondres.status(500)if an error happens after streaming or sending headers.
3. Common Traps to Avoid
Tracking down ERR_HTTP_HEADERS_SENT is much faster when you watch out for these recurring culprits:
- Missing
returninif / elsevalidation checks: Sending400or404withoutreturnlets the function continue to the200response at the bottom. - Unawaited promises or callbacks firing late: Starting an async operation without
awaitor firing a callback after a timeout/event already sent a response triggers a second write later. - Calling
next()inside acatchblock after already sendingres.status(...): Sending a response and then callingnext(err)hands a half-finished response to Express’s error handler, which then tries to send headers again.
TL;DR: Add return immediately after res.send() / res.json() / res.redirect(), avoid calling next() after responding, and guard error paths with if (res.headersSent).
Are you seeing this error inside an async/await route handler, a custom Express middleware, or a try/catch error block?
![How do you fix "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent" in Node.js Express? | A1Lab](/static/1787a778/assets/icons/icon-96x96.png)