Categories
JavaScript Answers

How to fix the ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client error with Node.js?

Spread the love

To fix the ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client error with Node.js, we make sure we only return a response once.

For instance, we write

if (!user) {
  errors.email = "User not found";
  res.status(404).json({ errors });
  return;
}

to call res.status and json to return the 404 status and the { errors } as the response body to send the response.

Then we use return to stop running the function to make sure another response isn’t sent.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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