Reputation: 117
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();
}
}
});
[object Object]
(node:4) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of null
I would appreciate any help!
Upvotes: 2
Views: 2280
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
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