# Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client (Node.js)

Thrown by Node's ServerResponse when code sets a header or status after the response already started. In Express apps the stack runs through express/lib/response.js, and the client usually received the first response just fine.

```
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (node:_http_outgoing:699:11)
    at ServerResponse.header (/app/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/app/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/app/node_modules/express/lib/response.js:278:15)
    at /app/src/routes/users.js:18:21 {
  code: 'ERR_HTTP_HEADERS_SENT'
}
```

## Quick fix

Make every code path send exactly one response: write return res.status(404).json(...) instead of calling res.json() and carrying on. The frame in your own route file marks the second send. In error middleware, hand off to next(err) when res.headersSent is already true.

1. Open the stack frame in your route file; that line is the second response.
2. Put return in front of every res.send, res.json, res.redirect and res.render.
3. Remove next() calls that follow a response in the same middleware.
4. Check that callbacks and timers cannot respond after another path already did.
5. In error handlers, check res.headersSent and call next(err) if it is true.

```js
app.get('/users/:id', async (req, res, next) => {
  try {
    const user = await db.user.findUnique({ where: { id: req.params.id } });
    if (!user) {
      return res.status(404).json({ error: 'not found' }); // return stops here
    }
    res.json(user);
  } catch (err) {
    next(err);
  }
});

app.use((err, req, res, next) => {
  if (res.headersSent) return next(err);
  res.status(500).json({ error: 'internal error' });
});
```

## Why it happens

### Missing return after an early response

if (!user) res.status(404).send('not found') without return lets execution fall through to the success path below it, which then calls res.json(user) and sends a second response.

### next() after responding

Middleware that sends a response and then calls next() passes the request to a later handler that responds again. Calling next(err) from a catch block after res.json already ran has the same effect.

### Sending inside a loop or a repeated callback

res.json inside forEach over results, or inside a callback that fires more than once (stream data events, a library that calls back on both success and error). The first iteration responds; every later one throws.

### Timeout middleware races the real handler

A timeout middleware sends a 503 and the slow handler finishes later and tries to send its own result. Nothing cancels the slower path, so both run to completion.

### Headers set after the body started

res.setHeader or res.cookie called after res.write or stream.pipe(res) already began. Headers go out with the first body chunk, so Node rejects any later header change.

## Other fixes

- With a timeout middleware, check res.headersSent (or req.timedout) before sending the late result.
- Pick one place to handle async errors: respond in the catch or call next(err), never both.
- Set cookies and headers before piping a stream or calling res.write.

## Same error, other wording

- `Error: Can't set headers after they are sent.`
- `Error [ERR_HTTP_HEADERS_SENT]: Cannot write headers after they are sent to the client`
- `Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client`

## Sources

- [Node.js HTTP: response.headersSent and setHeader](https://nodejs.org/api/http.html)
- [Node.js errors: ERR_HTTP_HEADERS_SENT](https://nodejs.org/api/errors.html)

---

To see this error the next time it happens in production, with the stack trace and the steps before it: Runheed records it and serves it to your coding agent over MCP. Setup instructions an agent can follow: https://runheed.com/SETUP.txt

Human-readable version: https://runheed.com/errors/err-http-headers-sent
