'Error [ERR_HTTP_HEADERS_SENT] while trying to login with wrong password

As backend for react, I have node v16.13.0 and express 4.17.2 and this express route for login

router.post("/login", async (req, res) => {
     try {
      const user = await User.findOne({ email: req.body.email });
      !user && res.status(404).json("user not found");
  
      const validPassword = await bcrypt.compare(req.body.password, user.password)

      !validPassword && res.status(400).json("wrong password")
  
      res.status(200).json(user)
    } catch (err) {
      res.status(500).json(err)
    }
  });

It works fine when the credentials are correct, but when the password is wrong I get:

::ffff:127.0.0.1 - - [05/Feb/2022:14:50:33 +0000] "POST /api/auth/login HTTP/1.1" 500 16
node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

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 (/home/me/Desktop/myapp/api/node_modules/express/lib/response.js:776:10)
    at ServerResponse.send (/home/me/Desktop/myapp/api/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/home/me/Desktop/myapp/api/node_modules/express/lib/response.js:267:15)
    at /home/me/Desktop/myapp/api/routes/auth.js:49:23
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

I'm wondering what is wrong here and how can i fix it?



Solution 1:[1]

when you pass the wrong credentials the res.json will be called twice and the error says that.

router.post("/login", async (req, res) => {
     try {
      const user = await User.findOne({ email: req.body.email });
      if(!user) {
         return res.status(404).json("user not found");
      }
  
      const validPassword = await bcrypt.compare(req.body.password, user.password)

      if(!validPassword) {
        return res.status(400).json("wrong password")
      } 
  
      res.status(200).json(user)
    } catch (err) {
      res.status(500).json(err)
    }
  });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Heartbit