Reputation: 339
hello i am creating token validation (JWT) and this error came up here is the code of JWT signing token:
if (user) {
const payload = user._id
console.log(payload)
console.log(process.env.SECRET)
const token = jwt.sign({id :payload}, process.env.SECRET, {
expiresIn: 10
})
console.log(token)
res.cookie('token', token, {
httpOnly: true
});
and verifying it (in middleware)
const token = req.body.token ||
req.query.token ||
req.headers['x-access-token'] ||
req.cookies.token;
if (!token) {
res.status(401).send({auth: false})
}
else{
jwt.verify(token, process.env.SECRET, function (err, decoded) {
if (err){
res.status(500).send({
message: err.message
})
}
req.userId = decoded.id
next()
})
}
i do not know the problem, i think i did everything according to docs but this error still shows up if anyone knows the solving for this problem i would be glad if i hear it thanks!
Upvotes: 0
Views: 4200
Reputation: 40404
If jwt.verify
fails, you're trying to access decoded.id
which does not exist. So issue a return
inside if(err)
otherwise the code will continue, calling next
& trying to access decoded.id
, triggering an error.
jwt.verify(token, process.env.SECRET, function(err, decoded) {
if (err) {
return res.status(500).send({
message: err.message
})
}
req.userId = decoded.id
next()
})
Upvotes: 3