How do you fix "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent" in Node.js Express? | A1Lab@FahadM to JavaScriptEnglish • 5 days ago

How do you fix "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent" in Node.js Express?

message-square
0

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent occurs in Express when your route handler or middleware attempts to send a second response (or set response headers/status) after HTTP headers have already been flushed to the client by an earlier res.json(), res.send(), res.redirect(), or res.end(). Fix it by returning early from branches after sending a response, ensuring middleware/async callbacks do not fall through after responding, and avoiding sending multiple responses on error.


1. Return Early After Sending a Response

The most common cause is forgetting return after an early validation or error response, allowing execution to continue and hit a second res.json() or res.send():

// Bad vs. Good: always return after sending a response in a branch
app.get("/users/:id", async (req, res, next) => {
  try {
    const userId = req.params.id;
    if (!userId) {
      return res.status(400).json({ error: "User ID is required" });
    }

    const user = await findUserById(userId);
    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }

    return res.status(200).json({ user });
  } catch (err) {
    if (res.headersSent) {
      return next(err);
    }
    return next(err);
  }
});
  • return res.status(...).json(...): Stops the rest of the current handler from running after the response is initiated.
  • Check res.headersSent: If headers were already sent before a late error occurs, avoid calling res.status(...).json(...) again and delegate to Express error handling (next(err)).

2. Guard Middleware, Async Flow, and catch Blocks

Another frequent cause is calling next() after sending a response in middleware, or sending a response inside try and then sending another response inside catch when something inside try throws after headers were sent:

// Middleware & async route guard to prevent duplicate responses
function requireAuth(req, res, next) {
  const token = req.headers.authorization;
  if (!token) {
    res.status(401).json({ error: "Unauthorized" });
    return; // Do not call next() after sending a response
  }
  next();
}

app.post("/orders", requireAuth, async (req, res, next) => {
  try {
    const order = await createOrder(req.body);
    return res.status(201).json({ order });
  } catch (err) {
    if (res.headersSent) {
      return;
    }
    return res.status(500).json({ error: "Failed to create order" });
  }
});
  • Never call next() after sending a response unless intentionally passing control to a downstream handler that has not responded yet.
  • Guard catch blocks with if (res.headersSent) return;: Prevents a second res.status(500) if an error happens after streaming or sending headers.

3. Common Traps to Avoid

Tracking down ERR_HTTP_HEADERS_SENT is much faster when you watch out for these recurring culprits:

  • Missing return in if / else validation checks: Sending 400 or 404 without return lets the function continue to the 200 response at the bottom.
  • Unawaited promises or callbacks firing late: Starting an async operation without await or firing a callback after a timeout/event already sent a response triggers a second write later.
  • Calling next() inside a catch block after already sending res.status(...): Sending a response and then calling next(err) hands a half-finished response to Express’s error handler, which then tries to send headers again.

TL;DR: Add return immediately after res.send() / res.json() / res.redirect(), avoid calling next() after responding, and guard error paths with if (res.headersSent).

Are you seeing this error inside an async/await route handler, a custom Express middleware, or a try/catch error block?