0

I have an express backend that checks if req.cookie.__session is undefined. If it is then I want it to return res.status(200).json({ verification: false }); if it is not undefined then I want it to check the cookie with jwt.verify() and handle it otherwise.

The problem is that if it is undefined then my try/catch catches and throws "Cannot read property '__session' " instead of returning the response that I want which is the ...verification: false. Any help is greatly appreciated. Thanks.

    try {
             let token = req.cookies.__session;
                console.log("req.cookies.__session", token);
                if (!token) {
                  console.log("no token cookie");
                  return res.status(200).json({ verification: false });
                }
                ... further code to verify and handle token if not undefined
         } catch (err) {...error handles}
Matthew
  • 95
  • 12
  • 1
    Did you forget to inject the [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware in your request handling pipeline? `req.cookies` is not a part of the base express library. – samthecodingman Oct 07 '21 at 08:02
  • It was as simple as that, thanks. – Matthew Oct 07 '21 at 09:30

0 Answers0