An Express 5 CSV export fails midway through streaming and the logs show ERR_HTTP_HEADERS_SENT instead of the real cause; why, and what should the error handler do?
answer
- the status line already left
- res.json sets a header
- the handler's own throw is forwarded
- check res.headersSent first
- let the default handler close it
basics
~20 sThe error handler tries res.status(500).json() after the 200 headers went out; res.json throws ERR_HTTP_HEADERS_SENT, which replaces the real error. Check res.headersSent first and return next(err): Express's default handler logs the original and destroys the socket.
solid answer
~40 sOnce the route has called `res.write()`, the 200 status line and headers are on the wire and `res.headersSent` is true. When the database cursor fails and the route calls `next(err)`, a handler that runs `res.status(500).json(...)` cannot win: `res.status` only changes a property nobody will send, and `res.json` hands off to `res.send`, which sets `Content-Type`, so Node throws `ERR_HTTP_HEADERS_SENT` ('Cannot set headers after they are sent to the client'). The router catches that throw and forwards it as the new error, so the built-in handler logs it, not the cursor failure, and then destroys the socket. Start the handler with `if (res.headersSent) return next(err)`: the original error is logged and the connection is closed, so the client sees a cut-off download instead of a file that looks complete.
code
javascript · 19 linesconst express = require('express');
const app = express();
app.get('/exports/orders.csv', (req, res, next) => {
res.status(200).type('text/csv');
res.write('id,total\n1,10\n');
// The cursor fails after the headers and first rows have been sent.
setTimeout(() => next(new Error('cursor lost')), 20);
});
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err); // built-in handler logs err and destroys the socket
}
res.status(500).json({ message: 'Export failed' });
});
app.listen(3000);go deeper
Recall that once a response has started, its status cannot change, and that res.headersSent tells an error handler whether that has happened.
Explain why res.json throws ERR_HTTP_HEADERS_SENT after a write, and that Express forwards a throw from an error handler as the new error.
Diagnose the misleading log, add the res.headersSent guard with next(err), and explain why a destroyed socket serves the client better than a clean end.
Decide which endpoints may stream at all, and make the headersSent guard part of the shared error handler every service imports.
## What 'headers sent' means in Express An HTTP response starts with a status line and headers. Node writes them the first time body bytes go out: on the first `res.write()`, or inside `res.send()`, `res.json()` or `res.end()`. From then on the status cannot change, and `res.headersSent`, a read-only property Express exposes from Node's response, is `true`. A streaming route commits early by design. A CSV export that writes rows as a database cursor yields them has sent `200` and `Content-Type: text/csv` before the first row, long before it knows whether the last row will arrive. ## How the real error disappears Trace a failure halfway through the export: 1. The route has written the header row and some data; `res.headersSent` is `true`. 2. The cursor fails, and the route calls `next(err)`. 3. The app's error handler runs `res.status(500).json({ message: 'Export failed' })`. 4. `res.status(500)` only assigns `res.statusCode`, which will never be sent. `res.json()` then hands the body to `res.send()`, which sets `Content-Type`, and Node throws **`ERR_HTTP_HEADERS_SENT`**: `Cannot set headers after they are sent to the client`. 5. The router invokes error handlers inside `try/catch` too, so it catches that throw and calls `next()` with the **new** error. 6. With no later handler, Express's built-in handler receives the `ERR_HTTP_HEADERS_SENT` error, logs *it*, sees that headers are sent, and destroys the socket. The client gets the same cut-off download either way. What changed is the log: the cursor failure was never written anywhere, and on-call engineers chase a header error that is only a side effect. ## The guard the Express guide prescribes The documented pattern is to delegate as soon as the response has started: - check `res.headersSent` at the **top** of every custom error handler; - if it is `true`, `return next(err)` and let Express's built-in handler finish; - log first if you want the error in your own structured logger with the request id, but still delegate. The built-in handler then logs the original error to stderr (unless the `env` setting is `'test'`) and **destroys the request socket**. For a chunked response that means the terminating chunk never arrives, so the client's HTTP library reports an aborted or incomplete response. The handler cannot do better: the status is gone, so a dropped connection is the only failure signal left. ## Fixes that look reasonable and are not | Attempt | What actually happens | |---|---| | `res.status(500).json(...)` | throws `ERR_HTTP_HEADERS_SENT`; the real error is replaced | | `res.status(500).end()` | ends the chunked body cleanly with status 200; the truncated CSV looks complete | | catch inside the route and do nothing | the request hangs with half a file | | `if (res.headersSent) return next(err)` | original error logged, connection destroyed, failure visible | `res.end()` deserves the warning: it writes the final chunk, the client sees a normal end of stream, and a half-written export is saved as if it were whole. ## Other ways to reach an error handler after a response The guard is not only for streams. The same state arises when: - a handler sends its response and then calls `next(err)` for some follow-up failure; - code calls `next(err)` twice; the Express guide notes that the default handler can then run even when a custom error handler is in place. In each case the custom handler meets `res.headersSent === true` and should delegate. When the response already finished cleanly, destroying the socket costs only that keep-alive connection, and the error is still logged. ## How to answer it in an interview A complete answer names the Express-specific pieces: `res.headersSent` as the test, `next(err)` as the hand-off, the built-in handler destroying the socket, and the fact that a throw inside an error handler becomes the new error. It also says why the client is better served by a dropped connection than by a clean `end()`. When the failure is not committed yet, buffering or pre-validating before the first write keeps it answerable with a proper status. Interviewers often push on two details. First, why the log line lies: the router invokes error handlers with the same `try/catch` it uses for routes, so a throw inside the handler is not swallowed but becomes the error that continues down the stack, and the original is never logged unless an earlier stage logged it. Second, what the client can rely on: with chunked transfer encoding, the only end-of-body marker is the final zero-length chunk, so a destroyed socket is detectable as an incomplete response, while a clean `res.end()` is not. Saying both shows you have read the logs of a real broken export rather than guessed at them.
- Why not end the broken export with res.end() in the error handler?`res.end()` writes the terminating chunk, so the client sees a normal end of stream on a 200 response and saves the truncated CSV as complete. Delegating with `next(err)` lets Express's built-in handler destroy the socket, which the client's HTTP library reports as an aborted response.
- How can the export return a proper 500 for failures that happen before any row is written?Do the work that can fail before the first `res.write()`: open the cursor and fetch the first batch, then start writing. Until something is written, `res.headersSent` is false and the error handler can still set a status and send a body.
- An error handler can still turn a streamed 200 into a 500.
- ERR_HTTP_HEADERS_SENT in the logs is the error that broke the export.
- Calling res.end() in the error handler is the clean way to stop a broken stream.
- A throw inside an error handler is ignored by Express.
- res.headersSent only matters for streaming routes.