I want to make a call every X amount of minutes from the client side to see if the JWT is still valid. I'm not sure how to do this in nodeJS. If I'm already authorized, how can i check if I'm still authorized.
You can have your client side decode the JWT and check an expiry
field and compare it with system time.
eg.
isExpired: (token) => {
if (token && jwt.decode(token)) {
const expiry = jwt.decode(token).exp;
const now = new Date();
return now.getTime() > expiry * 1000;
}
return false;
you can use npm install jsonwebtoken
or some other npm package on the client side to do this
An elegant solution to handle token expiration is when you set the token(in LocalStorage
or store(redux), or both) is also to have an Async function that runs exactly when the token expires. Something like this:
const logUserOut = token =>{
setTimeout(()=> MyLogoutFunction(), token.expiresIn)
}
This way you make sure that the user won't be logged when the token is no longer valid.
Create and endpoint that verifies the token is valid. You can use the the jsonwebtoken package.
import jwt from 'jsonwebtoken';
const verifyToken = (req, res) => {
const token = req.headers.authorization;
jwt.verify(token, SECRET_KEY, (err, decoded) => {
if (err) {
return res.status(401).send();
}
// can do something with the decoded data
})
}
router.post('/verify-token', verifyToken);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With