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.