How to Fix Cannot Set Headers in Express

Fix the "Cannot Set Headers After They Are Sent" error in Express.js fast. Learn the cause, see real solutions, and prevent it in your Node.js apps today.

A route can send an error response and then keep running toward its success response. The “Cannot set headers” error means code tried to change headers or send a response after the response was sent.

This article shows how to find calls that send a response and make each route branch send only one.

TL;DR: Send One Response for Each Request

The “Cannot set headers after they are sent to the client” error means a handler tried to change headers or send a response after output began. Node.js reports this as ERR_HTTP_HEADERS_SENT.

  • Return after sending a validation or error response.
  • In middleware, either send a response or call next(), not both.
  • Wait for asynchronous work before choosing the one response.

What Does the Cannot Set Headers Error Mean?

The table maps each cause to a diagnostic step. A branch that sends an error and then falls through to a success response is one common source.

CaseSymptomFix
Branch falls throughError response followed by success responseReturn from the response branch
Middleware continuesnext() runs before later response workChoose one action for the condition
Async fallback races resultImmediate response followed by callback responseRespond from the completed operation

How to Find and Fix a Second Express Response

Trace response-ending calls from the route into its middleware and callbacks, then make each branch choose one response path. Start by listing every place that can commit output.

Step 1: Find every response-ending call

Search the affected route and functions it calls for response methods and direct header writes. Include res.send(), res.json(), res.end(), res.redirect(), res.render(), res.sendFile(), and res.setHeader(). A method that sets a status alone does not finish a response, but a later response method still must be unique.

Step 2: Return after a branch sends a response

Sending a response does not terminate the handler, so execution can continue to later statements. The validation branch below returns its response and cannot reach the success statement for an invalid ID.

app.get('/orders/:id', (req, res) => {
  if (!/^\d+$/.test(req.params.id)) {
    return res.status(400).json({ error: 'Order id must be numeric' });
  }

  return res.status(200).json({ id: req.params.id });
});

I ran the single-response branch check from a named Node.js file. The invalid ID produced one 400 response and the valid ID produced one 200 response. Assertions make the check fail if either path produces more than one response.

Output:

Invalid order ID: one 400 response
Valid order ID: one 200 response
Terminal output showing one response for invalid and valid order IDs

The early return prevents the invalid-ID branch from reaching the success response. Apply the same structure to database or authorization checks, with each outcome returning from its own branch.

Step 3: Make middleware choose between next() and a response

Middleware passes control to the next handler with next(). An unauthenticated request ends here with 401. An authenticated request continues to the route shown after this function.

function requireUser(req, res, next) {
  if (!req.user) {
    return res.status(401).json({ error: 'Sign in required' });
  }

  return next();
}

Step 4: Keep asynchronous branches on one response path

Once the operation completes, send the response from its success path. Pass rejected work to error middleware.

app.get('/orders/:id', async (req, res, next) => {
  try {
    const order = await findOrder(req.params.id);
    return res.json(order);
  } catch (err) {
    return next(err);
  }
});

Express 5 forwards rejected promises from async route handlers to error middleware. With callback APIs, place the response in the callback’s success branch and pass failures to error handling.

Step 5: Handle errors after headers are sent

Streaming responses need separate treatment because bytes may already have reached the client before a later read or write fails. Express documents delegating an error when headers have been sent, since a replacement status or JSON body can no longer be started.

function errorHandler(err, req, res, next) {
  if (res.headersSent) {
    return next(err);
  }

  return res.status(500).json({ error: 'Request failed' });
}

What Else Should You Check?

Compare request IDs before changing code. A browser retry or a second request can look like duplicate handling. Correlate logs where each request enters the application.

Check these cases in order:

  1. For separate browser requests or a client retry, log a request identifier with each response path to distinguish them.
  2. Compare the logged request ID with the response call sites to rule out a second request.
  3. For a response helper that already wrote output, remove the caller’s later header change or response.

Also check whether a response is still open when code reaches a header change. Node.js tracks this state on ServerResponse. A true value confirms that headers were sent, but it does not identify which function sent them or make a second response safe.

A common source of confusion is the difference between preparing a response and sending it. Setting a status or header changes response metadata, while methods such as json(), send(), end(), redirect(), and render() can commit the response. A handler may call several metadata setters before the final send, but it must not try to replace committed headers afterward.

Pay attention to return values from helper functions. A helper that writes a response may return undefined, which can tempt the caller to interpret the result as a missing record and send a 404. Make the helper contract explicit: either it returns data and leaves response ownership to the route, or it handles the response and the route stops there.

Callbacks also change when code runs. A timeout, event listener, or database callback can run after the outer handler has already sent a response. In those cases, remove the early fallback or move response creation into the callback that knows the final result.

Do not use a delay to hide the race. Timing changes do not establish which branch owns the response.

When an exception appears only under load, look for two completion events rather than assuming the framework changed response behavior. For example, a timeout may send a gateway-style error while a slow database operation later returns successfully. Cancel work that is no longer needed where the API supports cancellation, and make the late callback avoid writing to a completed response.

Conclusion

When the stack trace points inside a view engine or response helper, inspect who called it and whether another path already rendered or sent output. Do not catch and ignore the second-send exception as a fix. That hides the faulty control flow and can leave clients with an incomplete response.

After changing the route, test both the branch that sends an error and the branch that succeeds. A single happy-path request may never execute the branch that caused the duplicate.

For implementation details, see the Express error-handling guide, the Express middleware guide, and Node.js’s HTTP response documentation.

FAQ

These short answers address the common follow-up questions when debugging the error.

What causes Cannot set headers after they are sent in Express?

Code tries to change headers or send another response after the response has already started. Look for a second response path in a branch, middleware function, callback, or error handler.

Does res.send() stop the route handler?

No. res.send() sends the response but does not stop JavaScript execution. Return from the branch or arrange the remaining logic in an else branch.

Can async code cause ERR_HTTP_HEADERS_SENT?

Yes. A route can respond before asynchronous work completes, then send again from its callback or promise. Wait for the work and keep success and error handling on exclusive paths.

Should I check res.headersSent before every response?

Use res.headersSent when error middleware may receive an error after output has started. It is not a replacement for removing duplicate response logic from the route.

Devdeep Ghosh
Devdeep Ghosh

Devdeep Ghosh covers Node.js development, including npm workflows, package configuration, Express troubleshooting, and server-side APIs. His work also covers concurrency and module systems.

Articles: 10