Error: Cannot set headers after they are sent to the client
Quick answer
You're calling `res.send()`, `res.json()`, or similar more than once in the same request — usually because a code path doesn't `return` after sending a response, and execution continues into a second response call.
What causes this error
Once Express sends a response, the HTTP request is considered complete. Any further attempt to call `res.send()`, `res.json()`, `res.redirect()`, etc. on that same response object throws this error — Node is telling you it already flushed headers to the client.
The Fix
// Wrong — missing return, both branches can execute
app.get('/user/:id', async (req, res) => {
const user = await getUser(req.params.id);
if (!user) {
res.status(404).json({ message: 'Not found' });
}
res.json(user); // still runs even after the 404!
});
// Correct
app.get('/user/:id', async (req, res) => {
const user = await getUser(req.params.id);
if (!user) {
return res.status(404).json({ message: 'Not found' });
}
return res.json(user);
});Common causes / variations
- Missing `return` before a conditional response inside an async handler
- Calling `next()` after already sending a response
- A timeout/error handler firing after the main handler already responded
Related errors
See also: req.body is undefined.
Was this fix helpful?
Comments
Loading comments...