ERR_HTTP_HEADERS_SENT in Next.js: what it means and why it matters
· Updated
- Next.js
- Node.js
- API Routes
- Production
This error shows up in server logs as "Cannot set headers after they are sent to the client", or ERR_HTTP_HEADERS_SENT. It often appears only in production, only sometimes, and the error message does not point clearly to the code that caused it.
What it means
When someone uses your app, the server receives a request and sends back one response. This error means the code tried to send a second response to the same request, after the first one was already sent.
Depending on the setup, the result can be anything from a harmless log line to a failed request or a crashed server process.
Why it often appears only in production
Most of the time, the code takes the normal path and sends one response. The second response only happens on less common paths: when something fails, when a request is slow, or when data is missing. These situations are rare in testing and common with real users and real traffic.
Common causes
- The code keeps running after an early answer. For example, it sends an "unauthorized" response but does not stop, and later also tries to send the normal response.
- An error in the middle of the work. The code sends an error response, and then another part of the code sends its own response too.
- Two layers both reply. A middleware and the page handler each think they are responsible for answering.
- Something runs after the response is done. A timer or background task that finishes later and tries to answer a request that is already closed.
The fix is usually small: making sure each request has exactly one response. The work is in finding where it happens.
When to ask for help
On its own, this error is often easy to fix. It is worth a closer look when it appears together with other production-only problems, such as memory that keeps growing or intermittent page errors. Those often share a cause.
If you would like someone to look at your app, a Production Health Audit is a low-risk way to start: I review the code and send you a written list of what I found and how to fix it.