Skip to content
node

Fix: Cannot set headers after they are sent to the client

Nov 16, 2022Abhishek EH2 Min Read
Fix: Cannot set headers after they are sent to the client

If you are new to Node.js and express, you might have come across the following error:

1Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

In this article, we will discuss the possible causes of the error and how to fix them.

Consider the following code:

1app.get("/api/orders/:orderId", function (req, res) {
2 if (!req.params.orderId.match(/[0-9]+/)) {
3 res.status(400).send({
4 error: "Order id is invalid",
5 })
6 }
7
8 // some other code..
9
10 res.send({
11 // order details
12 })
13})

At first look, the code looks perfectly fine. But when we run the code by passing a string in the place of the orderId (/api/orders/abcd), you will get the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.

The above error is occurring because when the order id is not a number, we are calling res.send() twice. Though res.send() sends the response back to the client, the code execution doesn't stop there. It continues with the execution of the remaining code and tries to return the response again to the client, hence the error.

We can fix this either by wrapping the rest of the code in an else block or adding a return at the end of the error handling:

1app.get("/api/orders/:orderId", function (req, res) {
2 if (!req.params.orderId.match(/[0-9]+/)) {
3 res.status(400).send({
4 error: "Order id is invalid",
5 })
6 } else {
7 res.send({
8 // order details
9 })
10 }
11})

OR

1app.get("/api/orders/:orderId", function (req, res) {
2 if (!req.params.orderId.match(/[0-9]+/)) {
3 res.status(400).send({
4 error: "Order id is invalid",
5 })
6 return
7 }
8 res.send({
9 // order details
10 })
11})

Another scenario where this error could occur is while you make a res.send() call after a promise is resolved.

1async function stall(stallTime = 3000) {
2 await new Promise(resolve => setTimeout(resolve, stallTime))
3}
4
5app.get("/api/invoice/:invoiceId", function (req, res) {
6 stall().then(() => {
7 res.send({
8 // invoice details
9 })
10 })
11
12 // Some other code
13 res.send({
14 //some other data
15 })
16})

The fix for the above code is to carefully add conditions and ensure that res.send() is called only once per each scenario.

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2022 CodingDeft.Com