EXPRESS GUIDE

How to Prevent “Cannot Set Headers After They Are Sent” in Express

By the HireReadyAI team · Last updated 6 October 2026 · 7 min read

Double responses, missing returns after res.json, and how to structure middleware safely.

What the error means

Express (via Node's HTTP response) throws when your code tries to write headers or a body after the response has already been sent. The first res.json, res.send, res.end, or res.redirect wins. A second write is a bug in control flow, not a framework mystery.

Common causes

  • Missing return after res.json(...) so later code sends again
  • Both success and error paths sending a response
  • Calling next() after already responding
  • Multiple middleware layers each trying to end the request
  • Async callbacks firing twice (forgotten abort, duplicated listeners)

Safe patterns

app.get('/user', async (req, res, next) => {
  try {
    const user = await findUser(req.params.id);
    if (!user) {
      return res.status(404).json({ error: 'Not found' });
    }
    return res.json(user);
  } catch (err) {
    return next(err);
  }
});

Return after every response. Let a single error middleware format failures. Avoid sending from both the route and a wrapping middleware for the same request.

Async handlers

Unhandled promise rejections in async routes can leave Express thinking the request is still open while your catch block also responds. Use try/catch or a wrap(asyncHandler) helper that forwards errors to next(err). Never mix callback-style and async-style completion for one request.

Middleware structure

Authentication middleware should either call next() or respond once — not both. Logging middleware should not end the response. Final error middleware should be registered last with four arguments (err, req, res, next).

Fix checklist

  • Search the handler for every res.* send path and ensure mutual exclusion
  • Add return before responses
  • Centralize errors
  • Write a test that hits both success and failure branches

All guides · HireReadyAI home