Node.jsExpressError Fix2026 Updated

Error: Cannot set headers after they are sent— Fixed [Complete Guide 2026]

January 20265 min readExpress · Node.js · All OS

⚡ The Fix — One Rule

Add return before every response. This stops execution immediately and prevents a second response from being sent:

Every Express route handler
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?

Terminal 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:9

HTTP 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.

1

Add return Before Every Response

The universal fix — applies to all cases
2 min
routes/users.js
// ❌ 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.

2

Fix if/else Chains in Route Handlers

Multiple conditions — each needs return
2 min
routes/auth.js
// ❌ 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 })
  }
})
3

Fix Async Routes with try/catch

Async routes sending response in both try and catch
2 min
routes/data.js
// ❌ 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
})
4

Fix Middleware Calling next() After Response

Auth middleware, logging middleware
2 min

Middleware should either call next() OR send a response — never both. If you send a response in middleware, do not call next().

middleware/auth.js
// ❌ 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
}
5

Use res.headersSent as a Safety Guard

Defensive check for complex routes
1 min

In complex routes with multiple async callbacks, use res.headersSent to check if a response was already sent before sending another.

routes/complex.js
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.

6

Fix Callbacks and Event Handlers

Legacy callback-style code
3 min

In callback-based code (not async/await), it is easy to accidentally call the response in both the error and success branches.

routes/file.js
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

Frequently Asked Questions

What causes Cannot set headers after they are sent?+
Your code sent two responses to the same request. HTTP only allows one response per request. This happens when you forget to add return before res.json() or res.send(), allowing code to continue executing and send a second response.
How do I fix headers already sent in Express?+
Add return before every response: return res.status(400).json({ error: 'message' }). This stops code execution immediately after the first response is sent.
How do I prevent double response in Express middleware?+
Never call next() after sending a response. If you send a response in middleware, return immediately without calling next: return res.status(401).json({ error: 'Unauthorized' })
What is res.headersSent in Express?+
res.headersSent is a boolean that is true if a response has already been sent for the current request. You can use it as a safety guard: if (!res.headersSent) { res.json(data) }
Cannot set headers error in async route — how to fix?+
Wrap the route in try/catch and add return before every res.json() call: try { return res.json(data) } catch(err) { return res.status(500).json({ error: err.message }) }
Error appears randomly — not on every request?+
This usually means the double response only happens under certain conditions — like when an async operation completes after a timeout response was already sent. Add return before every response in the route and check for race conditions in async code.

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