ERR_HTTP_HEADERS_SENT
Cannot set headers after they are sent to the client.
Usually happens because:
- ☑ Multiple res.send()
- ☑ Failing to Return
- ☑ Response Timing
🔍 Quick Checklist:
What is ERR_HTTP_HEADERS_SENT?
The ERR_HTTP_HEADERS_SENT error is thrown when your server code attempts to send headers or set status codes on a response object after it has already initiated transmission or fully completed the request.
Common Causes
- Multiple res.send(): Issuing multiple res.send() or res.json() actions within a single route execution stream.
- Failing to Return: Leaving out the return keyword on validation checks, allowing execution flow to hit downstream response statements.
- Response Timing: Calling redirect or status changes inside asynchronous callbacks after the response was already dispatched.
| Cause | Frequency |
|---|---|
| Multiple res.send() | ⭐⭐⭐⭐⭐ |
| Failing to Return | ⭐⭐⭐⭐ |
| Response Timing | ⭐⭐⭐ |
Common Mistakes
- Forgetting return keywords on early abort validations.
- Attempting redirects inside async callback timeouts after the main route handler has finished.
How to Fix
Framework-Specific Examples
Utilizing defensive coding returns to prevent double response flushes.
app.get('/user/:id', (req, res) => {
if (req.params.id === 'admin') {
return res.status(403).json({ error: 'Unauthorized access.' });
}
return res.json({ id: req.params.id, name: 'Guest' });
});Server Configuration Examples
Nginx proxy servers are not affected by this application-level header exception.
# Handled entirely by Node app routersBest Practices
- Use lint rules to check path branches.
- Consistently return all response method calls (e.g. `return res.json(...)`).
Frequently Asked Questions (FAQ)
Q: What triggers ERR_HTTP_HEADERS_SENT?
It is triggered when code tries to modify HTTP headers or status code values after Node has already started transmitting the body payload packets to the browser.
Q: Does res.send() stop code execution?
No! `res.send()` is a normal function call. It prepares and flushes headers and body, but the rest of your JavaScript function continues executing. You must use `return` to stop execution.
Q: How do I fix ERR_HTTP_HEADERS_SENT inside async loops?
Ensure you do not call `res.send()` inside a `.forEach()` or `.map()` loop. Use database aggregations or compile results into an array first, then send one response.
Q: Can middleware trigger this error?
Yes. If a middleware sends a response (e.g. auth check failing) but calls `next()` anyway, the downstream route handler will try to send a second response, triggering the error.