Sometimes, we want to check if token expired using the Node.js JWT library.
In this article, we’ll look at how to check if token expired using the Node.js JWT library.
How to check if token expired using the Node.js JWT library?
To check if token expired using the Node.js JWT library, we can use the jwt.verify
method.
For instance, we write
const jwt = require('jsonwebtoken')
const util = require('util');
const jwtVerifyAsync = util.promisify(jwt.verify);
router.use(async (req, res, next) => {
const token = getToken(req)
try {
req.auth = await jwtVerifyAsync(token, req.app.get('your-secret'))
} catch (err) {
throw new Error(err)
}
next()
});
to call util.promisify
to convert the jwt.verify
method to a function that returns a promise and assign it to jwtVerifyAsync
.
Then we call jwtVerifyAsync
with the token
and the token secret to check if the token is valid.
If it’s expired, then it’s considered invalid and an error will be thrown.
And when an error is thrown we use the catch
block to catch it and rethrow it with throw
.
Otherwise, we call next
to call the next middleware.
Conclusion
To check if token expired using the Node.js JWT library, we can use the jwt.verify
method.