When a request has an unread body, finalhandler waits for the request to finish before sending the response.
If another middleware or asynchronous operation sends the response headers during this wait, res.headersSent can be false when finalhandler is called and true when the onFinished callback runs.
The callback does not check res.headersSent again. It attempts to modify the already-sent headers with res.removeHeader(), causing the following exception:
ERR_HTTP_HEADERS_SENT
Cannot remove headers after they are sent to the client
If the exception is not caught, the Node.js process may exit.
Conditions
- The request body has not been fully read.
- finalhandler registers a response write with
onFinished.
- Another operation sends the response headers before the request finishes.
- The request finishes and the registered write runs.
Expected behavior
If the response headers have already been sent when the onFinished callback runs, finalhandler should leave the response unchanged and should not throw an exception.
Related
#36 explains why finalhandler waits for the request body to be fully read before sending the response.
This issue concerns the response state changing during that wait, rather than the wait itself.
When a request has an unread body, finalhandler waits for the request to finish before sending the response.
If another middleware or asynchronous operation sends the response headers during this wait,
res.headersSentcan befalsewhen finalhandler is called andtruewhen theonFinishedcallback runs.The callback does not check
res.headersSentagain. It attempts to modify the already-sent headers withres.removeHeader(), causing the following exception:If the exception is not caught, the Node.js process may exit.
Conditions
onFinished.Expected behavior
If the response headers have already been sent when the
onFinishedcallback runs, finalhandler should leave the response unchanged and should not throw an exception.Related
#36 explains why finalhandler waits for the request body to be fully read before sending the response.
This issue concerns the response state changing during that wait, rather than the wait itself.