Javascript Check if the Date is already Expired in Token

Viewed 18426

Good day,

I'm using jwt in my authentication. I already decoded my token but the problem is, I want to check if the token exp is already expired or not.

var decodedToken = localStorage.getItem('user_token');

console.log(decodedToken.exp) // writes 1540360205

Thank you in advance.

4 Answers

It appears that the exp claim of your JWT tokens is bearing a UNIX timestamp, in seconds. To check if a given JWT is expired then you can just compare against the current date as a UNIX timestamp:

var decodedToken = localStorage.getItem('user_token');
if (decodedToken.exp < new Date()/1000) {
    console.log("EXPIRED");
}

This should get you the local time then you can compare it with current date and time and check if the token has expired

var tokenDate = new Date(parseInt(localstorage.getItem('user_token')) * 1000)

I assume that the value of decodedToken.exp is a UNIX timestamp of the token expiration date and thus you could just do the following:

...
var date = new Date();
// date.getTime() is in milliseconds and thus we've got to divide by 1000
if(decodedToken.exp<date.getTime()/1000){
    console.log('The token has expired');
}else{
    console.log('The token is still valid');
}

you can compare using Date.now() as follows

     decodedToken.exp * 1000 < Date.now()

PS: I've multiplied exp * 1000 to get it in ms.

Related