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

That particular error occurs whenever you try to send more than one response to the same request and is usually caused by improper asynchronous code.

The code you show in your question does not appear like it would cause that error, but I do see code in a different route here that would cause that error.

Where you have this:

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

You need to change it to:

if (!user) {
  errors.email = "User not found";
  res.status(404).json({ errors });
  // stop further execution in this callback
  return;
}

You don't want the code to continue after you've done res.status(404).json({ errors }); because it will then try to send another response.


In addition, everywhere you have this:

if (err) throw err;

inside an async callback, you need to replace that with something that actually sends an error response such as:

if (err) {
    console.log(err);
    res.sendStatus(500);
    return;
}

throwing inside an async callback just goes back into the node.js event system and isn't thrown to anywhere that you can actually catch it. Further, it doesn't send a response to the http request. In otherwords, it doesn't really do what the server is supposed to do. So, do yourself a favor and never write that code in your server. When you get an error, send an error response.


Since it looks like you may be new here, I wanted to compliment you on including a link to your full source code at https://github.com/lourdesr/devlog because it's only by looking at that that I was able to see this place where the error is occuring.


I was receiving this error because of a foolish mistake on my part. I need to be more careful when referencing my other working code. The truly embarrassing part is how long I spent trying to figure out the cause of the error. Ouf!

Bad:

return res
  .send(C.Status.OK)
  .json({ item });

Good:

return res
  .status(C.Status.OK)
  .json({ item });

Use ctrl + F hotkey and find all 'res.' keywords then replace them with a prefix of 'return ',

change  all 'res.' to  'return res.'

something like this:

res.send() change to --> return res.send()

maybe you have 'res.' in some block, like if() statement