Skip to content
Advertisement

Cannot set headers after they are sent to the client (Node.js)

So basically when I try to log a user in and I type the password or username wrong and then I try to log in with correct credentials I get this error.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (D:ecom websiteecom backendnode_modulesexpresslibresponse.js:794:10)
    at ServerResponse.send (D:ecom websiteecom backendnode_modulesexpresslibresponse.js:174:12)
    at ServerResponse.json (D:ecom websiteecom backendnode_modulesexpresslibresponse.js:278:15)
    at D:ecom websiteecom backendroutesauth.js:57:21
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

And this is my code in auth.js

//LOGIN

router.post('/login', async (req, res) => {
  try {
    const user = await User.findOne({
      username: req.body.username,
    });

    !user && res.status(401).json('Wrong User Name');

    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );
    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

    const inputPassword = req.body.password;

    originalPassword != inputPassword && res.status(401).json('Wrong Password');

    const accessToken = jwt.sign(
      {
        id: user._id,
        isAdmin: user.isAdmin,
      },
      process.env.JWT_SEC,
      { expiresIn: '3d' }
    );

    const { password, ...others } = user._doc;
    res.status(200).json({ ...others, accessToken });
  } catch (err) {
    res.status(500).json(err);
  }
});

What should I do? Is something wrong with my code?

Advertisement

Answer

!user && res.status(401).json('Wrong User Name');

as a statement is IMHO quite bad style. And as you see, it leads to errors, because your code doesn’t step out of this handler after having sent the headers. It just continues with the next statment and eventually reaches another res.status(...). This will try to set some headers again, which isn’t allowed. And that’s what the error message is telling you.

Use

if (!user) {
  return res.status(401).json('Wrong User Name');
}

instead. This will return from handler and not execute the remaining code in your function … Same of course for all other instances where you use this pattern.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement