Error: Cannot set headers after they are sent— Fixed [Complete Guide 2026]
⚡ The Fix — One Rule
Add return before every response. This stops execution immediately and prevents a second response from being sent:
app.get('/user/:id', async (req, res) => {
if (!req.params.id) {
return res.status(400).json({ error: 'ID required' }) // ← return!
}
const user = await User.findById(req.params.id)
if (!user) {
return res.status(404).json({ error: 'Not found' }) // ← return!
}
return res.json(user) // ← return!
})What Causes This Error?
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/node_modules/express/lib/response.js:794:10)
at ServerResponse.json (/node_modules/express/lib/response.js:267:10)
at /Users/you/projects/api/routes/users.js:25:9HTTP only allows one response per request. This error means your code called res.json(), res.send(), or res.redirect() twice on the same request. The second call fails because the response headers are already sent and cannot be changed.
The root cause is always the same: missing return statements. When you forget to add return before sending a response, JavaScript continues executing the function and hits another response call.
Add return Before Every Response
The universal fix — applies to all cases// ❌ WRONG — multiple responses possible
app.get('/user/:id', async (req, res) => {
if (!req.params.id) {
res.status(400).json({ error: 'ID required' })
// code continues! hits the line below too
}
const user = await User.findById(req.params.id)
res.json(user) // second response → ERROR
})
// ✅ CORRECT — return stops execution
app.get('/user/:id', async (req, res) => {
if (!req.params.id) {
return res.status(400).json({ error: 'ID required' })
// execution stops here — no more code runs
}
const user = await User.findById(req.params.id)
return res.json(user)
})Treat return res.json() as a single unit. Never write res.json() without return in front of it — unless it is the last line of the function and there is nothing else that could run after it.
Fix if/else Chains in Route Handlers
Multiple conditions — each needs return// ❌ WRONG — both conditions can run
app.post('/login', async (req, res) => {
if (!req.body.email) {
res.status(400).json({ error: 'Email required' })
// falls through to next if!
}
if (!req.body.password) {
res.status(400).json({ error: 'Password required' })
// double response!
}
// even more code below...
const user = await User.findOne({ email: req.body.email })
res.json(user) // third response!
})
// ✅ CORRECT — each condition returns immediately
app.post('/login', async (req, res) => {
if (!req.body.email) {
return res.status(400).json({ error: 'Email required' })
}
if (!req.body.password) {
return res.status(400).json({ error: 'Password required' })
}
try {
const user = await User.findOne({ email: req.body.email })
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' })
}
return res.json({ token: 'abc123' })
} catch (err) {
return res.status(500).json({ error: err.message })
}
})Fix Async Routes with try/catch
Async routes sending response in both try and catch// ❌ WRONG — response in both try and the code after
app.get('/data', async (req, res) => {
try {
const data = await fetchData()
res.json(data) // first response
} catch (err) {
res.status(500).json({ error: err.message }) // second response!
}
res.json({ done: true }) // third response!
})
// ✅ CORRECT — return in try, return in catch, nothing after
app.get('/data', async (req, res) => {
try {
const data = await fetchData()
return res.json(data)
} catch (err) {
return res.status(500).json({ error: err.message })
}
// nothing here — the try/catch covers all cases
})Fix Middleware Calling next() After Response
Auth middleware, logging middlewareMiddleware should either call next() OR send a response — never both. If you send a response in middleware, do not call next().
// ❌ WRONG — sends response AND calls next()
function authMiddleware(req, res, next) {
if (!req.headers.authorization) {
res.status(401).json({ error: 'Unauthorized' })
next() // ← wrong! calls the route handler too → double response
}
next() // calls next even when unauthorized
}
// ✅ CORRECT — either respond OR call next, never both
function authMiddleware(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' })
// return stops here — next() never called
}
next() // only reaches here if authorized
}Use res.headersSent as a Safety Guard
Defensive check for complex routesIn complex routes with multiple async callbacks, use res.headersSent to check if a response was already sent before sending another.
app.get('/complex', async (req, res) => {
// Start a timeout fallback
const timeout = setTimeout(() => {
if (!res.headersSent) {
res.status(408).json({ error: 'Request timeout' })
}
}, 5000)
try {
const data = await longRunningOperation()
clearTimeout(timeout) // clear timeout if operation completed
if (!res.headersSent) { // guard — timeout might have fired
return res.json(data)
}
} catch (err) {
clearTimeout(timeout)
if (!res.headersSent) {
return res.status(500).json({ error: err.message })
}
}
})res.headersSent should be a safety net — not your primary pattern. Fix the root cause with return statements first. Use headersSent only in routes with genuine async race conditions like timeouts.
Fix Callbacks and Event Handlers
Legacy callback-style codeIn callback-based code (not async/await), it is easy to accidentally call the response in both the error and success branches.
const fs = require('fs')
// ❌ WRONG — response called even when err returns
app.get('/file', (req, res) => {
fs.readFile('./data.json', (err, data) => {
if (err) {
res.status(500).json({ error: 'Read failed' })
// does NOT return — falls through
}
res.json(JSON.parse(data)) // called even on error!
})
})
// ✅ CORRECT — return after error response
app.get('/file', (req, res) => {
fs.readFile('./data.json', (err, data) => {
if (err) {
return res.status(500).json({ error: 'Read failed' })
// returns here — success line never runs
}
return res.json(JSON.parse(data))
})
})Common Patterns — Right vs Wrong
Quick Reference — Always add return
| ❌ Wrong | ✅ Correct |
|---|---|
| res.json(data) | return res.json(data) |
| res.send(text) | return res.send(text) |
| res.status(404).json({...}) | return res.status(404).json({...}) |
| res.redirect('/login') | return res.redirect('/login') |
| res.status(401).end() | return res.status(401).end() |
How to Prevent This Error
- Add return before every res.json(), res.send(), res.redirect(), and res.end()
- Never call next() after sending a response in middleware
- Use if/else instead of multiple if blocks when conditions are mutually exclusive
- Wrap async routes in try/catch with return in both try and catch
- Use ESLint with the consistent-return rule to catch missing return statements
- Use res.headersSent as a safety check in routes with async race conditions
Frequently Asked Questions
What causes Cannot set headers after they are sent?+−
How do I fix headers already sent in Express?+−
How do I prevent double response in Express middleware?+−
What is res.headersSent in Express?+−
Cannot set headers error in async route — how to fix?+−
Error appears randomly — not on every request?+−
Need Expert Help?
We Build Production-Grade Express APIs
Softplix builds full-stack Node.js applications. Struggling with complex Express middleware or API architecture? We can help.
Talk to an Engineer