Scaleup Infotech
Scaleup Infotech.
Back to Blog
Bug Fixes7 min read

Fix 'Cannot set headers after they are sent to the client' in Express

Scaleup Infotech

Scaleup Infotech

Software & Marketing Agency

Apr 09, 2026
Fix 'Cannot set headers after they are sent to the client' in Express
Node.jsExpressAsync

This error means your route handler called res.send/res.json/res.redirect more than once for a single request. An HTTP response can only be sent once. The fix is to make sure every path ends in exactly one response.

The Error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Cause 1: Missing return After res.send

javascript
// ❌ Both blocks can run
app.get("/user", (req, res) => {
  if (!req.user) res.status(401).json({ error: "Unauthorized" });
  res.json(req.user); // runs even after the 401 above
});

// ✅ Return to stop execution
app.get("/user", (req, res) => {
  if (!req.user) return res.status(401).json({ error: "Unauthorized" });
  return res.json(req.user);
});

Cause 2: Responding in a Loop or Callback

Calling res.send inside a forEach or multiple async callbacks fires it repeatedly. Collect results first, then respond once after the loop.

Cause 3: Responding Then Continuing Async Work

javascript
// ✅ One response, guarded by try/catch
app.post("/save", async (req, res) => {
  try {
    const doc = await save(req.body);
    return res.status(201).json(doc);
  } catch (err) {
    return res.status(500).json({ error: err.message });
  }
});

Rule of Thumb

Always return your response calls. It turns 'maybe two responses' into a compile-time-obvious single exit point.

Share this article:

Keep Reading

Ready to implement these ideas?

Work With Scaleup Infotech