Skip to content

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client – How to fix?

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client – This error actually means you have already sent response to the client and you’re trying to send response again back to the client.

Take this code for an example:

Advertisements
 if(total > 0) {
             res.status(200).send({status: 0, message: "Messages available"});
        }
   res.status(503).send({status: 1, message: "Messages not available!"});

In this code snippet, I’m trying to send 200 OK response if total > 0 and 503 Unavailable when total <= 0. When 200 OK is sent, this code will again try to send 503 Unavailable in the response. This would result in Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client error.

To fix this you can add return before res.status().send()

 if(total > 0) {
             return res.status(200).send({status: 0, message: "Messages available"});
        }
  return res.status(503).send({status: 1, message: "Messages not available!"});
Advertisements

Or you can use if..else in this particular code snippet.

 if(total > 0) {
             res.status(200).send({status: 0, message: "Messages available"});
 } else {
   res.status(503).send({status: 1, message: "Messages not available!"});
 }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.