Here is a solution with jwt-decode library by comparing the exp attributes in the JWT token with current time. (JWT token is simply a Base64 encoded string)
-
Install jwt-decode (
npm install jwt-decode --save)let token = localStorage.getItem(TOKEN); let decodedToken = jwt_decode(token); console.log("Decoded Token", decodedToken); let currentDate = new Date(); // JWT exp is in seconds if (decodedToken.exp * 1000 < currentDate.getTime()) { console.log("Token expired."); } else { console.log("Valid token"); result = true; }
IMPORTANT: jwt-decode doesn’t validate the token, any well formed JWT can be decoded. You should validate the token in your server-side logic by using something like express-jwt, koa-jwt, Owin Bearer JWT, etc.