Lars Mohammed
Lars Mohammed

Reputation: 117

JWT decode returns "[object Object]"

I'm trying to decode a JSON web token which is sent to my rest API server. However, when I try to use the _id property sent inside the web token I can't get it to work. This is the code I'm using:

  jwt.verify(token, process.env.TOKEN_SECRET, { complete: true }, async (err, decoded) => {
    console.log(decoded)
    if (err) {
      res.status(400).json({
        error: 'Token is not valid'
      });
      return
    } else {

      // Verify user exists
      const userExists = await User.findById(decoded._id);
      if (userExists == [] || !userExists){
        res.status(400).json({
          error: 'Token is not valid'
        });
        return
      } else {
        req.decoded = decoded;
        next();
      }
    }
  });


This is the console log I'm getting: [object Object]
And this is the error which is logged: (node:4) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of null I would appreciate any help!

Upvotes: 2

Views: 2280

Answers (2)

the-hyphen-user
the-hyphen-user

Reputation: 118

I had this same issue and it turned out the token was bad from the start.

My problem was the token I was signing from the server had a .toString() that needed to get removed.

jwt.sign({ user: User.toString() }, secretKey, {
    expiresIn: '24h'
});

VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV

jwt.sign({ user: User }, secretKey, {
        expiresIn: '24h'
    });

Upvotes: 2

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5708

Instead of logging information like this: console.log(decoded)

You should do it like this: console.log(JSON.stringify(decoded))

You should get your object nicely formatted in console.

Upvotes: 5

Related Questions