Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Node.js · updated 2026-11-03
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.
- Open the stack frame in your route file; that line is the second response.
- Put return in front of every res.send, res.json, res.redirect and res.render.
- Remove next() calls that follow a response in the same middleware.
- Check that callbacks and timers cannot respond after another path already did.
- In error handlers, check res.headersSent and call next(err) if it is true.
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' });
});Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/err-http-headers-sent.md and fix this error in this project.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
Let your coding agent catch the next one
Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:
> Find ERR_HTTP_HEADERS_SENT errors in production, identify the route and the two code paths that respond to the same request, and add the missing return or res.headersSent check.
Setup for Node.js and Express, Fastify or Vercel Functions, then have your agent fix and resolve it.
Related errors
- [UnhandledPromiseRejection: This error originated either by throwing inside of an async...
- TypeError: Cannot read properties of undefined (reading 'x')
- Error: read ECONNRESET
More in Network and HTTP
- Error: connect ECONNREFUSED 127.0.0.1:5432Node.js
- Error: connect ETIMEDOUT 10.0.4.12:5432Node.js
- TypeError: fetch failedNode.js
- Error: self-signed certificate in certificate chainNode.js
- Error: getaddrinfo ENOTFOUND api.example.comNode.js
- Error: write EPIPENode.js
- Access to fetch at 'https://api.example.com/orders' from origin 'https://app.example.com'...Node.js
- AxiosError: Request failed with status code 401Node.js
- FunctionsHttpError: Edge Function returned a non-2xx status codeSupabase
- requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.example.com'...Python
- httpx.ReadTimeout: The read operation timed outPython
- ConnectionResetError: [Errno 104] Connection reset by peerPython
- BrokenPipeError: [Errno 32] Broken pipePython
- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer...Python
- 422 Unprocessable Entity: {"detail":[{"type":"missing","loc":["body","email"],"msg":"Field...Python
- No signatures found matching the expected signature for payload. Are you passing the raw...Node.js
- TokenExpiredError: jwt expiredNode.js
- Error: 429 You exceeded your current quota, please check your plan and billing details.Node.js
Other error topics
- sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due...Databases
- [ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379Databases
- error: infinite recursion detected in policy for relation "members"Databases
- ImportError: cannot import name 'x' from partially initialized module 'y' (most likely...Imports and modules
- Error: Could not load the "sharp" module using the linux-x64 runtimeImports and modules
- Module not found: Can't resolve 'fs'Imports and modules
- ReferenceError: window is not definedReact and Next.js rendering
- TypeError: Failed to parse URL from /api/ordersReact and Next.js rendering
- ChunkLoadError: Loading chunk 4512 failed. (error...React and Next.js rendering
- java.lang.NullPointerException: Cannot invoke "String.toLowerCase()" because the return...Undefined, None and type errors
- AttributeError: 'NoneType' object has no attribute 'x'Undefined, None and type errors
- RuntimeError: dictionary changed size during iterationUndefined, None and type errors
- SyntaxError: Unexpected end of JSON inputJSON, parsing and validation
- RangeError: Invalid time valueJSON, parsing and validation
- pydantic_core._pydantic_core.ValidationError: 1 validation error for User email Field...JSON, parsing and validation
- PermissionError: [Errno 13] Permission denied: '/app/data/report.csv'Memory, async and the process
- RecursionError: maximum recursion depth exceededMemory, async and the process
- MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error...Memory, async and the process
- MCP error -32602: Input validation error: Invalid arguments for tool get_orderMCP servers and clients
- Not Acceptable: Client must accept both application/json and text/event-streamMCP servers and clients
- Bad Request: Unsupported protocol version: 2026-07-28MCP servers and clients
Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.
References: Node.js HTTP: response.headersSent and setHeader, Node.js errors: ERR_HTTP_HEADERS_SENT
Spotted a mistake? Email hello@greatwork.company. About Runheed.