Express res.headersSent Property
What you’ll learn
- What
res.headersSenttells you during the response lifecycle. - How to guard against duplicate response writes.
- How to use it safely in async callbacks and error handlers.
- How it works with
res.send(), streams, and middleware chains.
Usage pattern
javascript
if (!res.headersSent) {
res.status(500).send('Something went wrong');
}1
Check state before writing fallback response
javascript
app.get('/profile', function (req, res) {
res.send('Profile response');
if (!res.headersSent) {
res.send('Fallback'); // this block will not run
}
});2
Use guard in async callback
javascript
app.get('/file', function (req, res) {
res.download('files/manual.pdf', function (err) {
if (err && !res.headersSent) {
res.status(404).send('File not found');
}
});
});3
Guard in centralized error handler
javascript
app.use(function (err, req, res, next) {
if (res.headersSent) return next(err);
res.status(500).json({ error: 'Internal Server Error' });
});⚠️ Common pitfalls
res.headersSentis a guard, not a replacement for good control flow and early returns.- Do not attempt to set headers after they are sent; use checks in async branches.
- Be careful with mixed sync/async paths that may each try to respond.
❓ FAQ
It is a boolean property indicating whether HTTP response headers have already been sent.
It helps prevent double-send errors when multiple async paths try to respond.
After Express/Node starts sending the response, such as after res.send(), res.json(), or stream writes.
No, but it is an important guard in callbacks and error handlers.
Yes, return statements keep control flow clear and reduce accidental extra writes.
Did you know?
res.headersSent becomes true once the response headers are flushed to the client.
4 people found this page helpful
