Guard error responses
Custom error middleware needs to decide whether it can render or send an error response.
Express.js · Pipe
res.headersSent is a Boolean that tells you whether the response’s HTTP headers have already been sent. Check it before attempting response handling that could write headers again.
res.headersSent is a Boolean response property that reports whether Express has sent HTTP headers to the client. It is false before res.send() commits the response and true afterward, making it useful when deciding whether an error handler can still construct a normal response.
res.headersSentBoolean property
const express = require('express');
const app = express();
app.get('/', (req, res) => {
console.log(res.headersSent); // false
res.send('OK');
console.log(res.headersSent); // true
});
app.listen(3000);Run the server and request / to observe the property before and after sending the response.
Custom error middleware needs to decide whether it can render or send an error response.
Debugging response flow in a route handler.
Avoiding response writes after a response has begun.
res.headersSent represent?It is a Boolean property on the response object. It indicates whether the application has sent HTTP headers for that response.
Follow-up: What should a custom error handler do when it is true? It should pass the error to the default Express error handler with next(err) rather than trying to write a new response.
res.send()?Before res.send() in the documented example, the property is false. After res.send('OK'), it is true because the response headers have been sent.
Follow-up: Does checking it alone guarantee that no response body bytes were sent? No; it specifically reports header transmission, not complete-body transmission.
res.headersSent used in error handling?Use it in custom error middleware to distinguish responses that can still be formatted from responses whose headers are already committed. If it is true, call next(err) so Express's default error handling can take over.
Follow-up: Why not call res.status(500).send() unconditionally? A second response may be invalid once the headers have already been sent.
res.send()res.status()res.render()next(err)Error handling