Search code examples
javascriptjwtlocal-storageaccess-token

How to check access token validity for JWT


I want to test the access token for following conditions

  1. access_token key doesn't exist in local storage
  2. key exists but the value is undefined
  3. value is string but not in the correct format
  4. value is a valid token but is expired Here is the code I wrote
// Root.js
const curr_access_token_user = (typeof localStorage.getItem('access_token')
    === 'undefined') ? null :
      (Date.now() >= parseJwt(localStorage.getItem('access_token')).exp *1000 ?
        null : parseJwt(localStorage.getItem('access_token')).username);

parseJWT parses a valid token.
When I remove the access_token from my browser or set the value to undefined, the code still goes into parseJWT function. What is wrong with my code? isn't typeof the correct function to use in these conditions? Thanks


Solution

  • The issue here is that the localStorage.getItem('access_token') will return null if the 'access_token' key does not exist in localStorage and it will return 'undefined' string if the value of the key is set to undefined. The typeof operator will then return 'object' for null and 'string' for 'undefined'. It will never return 'undefined'. Because the typeof operator in JavaScript returns a string indicating the type of the unevaluated operand, that means it will return 'undefined' only if the variable itself is not declared.

    So, if you want to handle the conditions where the key doesn't exist or the value is undefined, you should check the value of localStorage.getItem('access_token') directly instead of using typeof.

    You can fix the code like this:

    let access_token = localStorage.getItem('access_token');
    let curr_access_token_user;
    
    if (access_token === null || access_token === 'undefined') {
      curr_access_token_user = null;
    } else {
      try {
        let decodedToken = parseJwt(access_token);
        if (Date.now() >= decodedToken.exp * 1000) {
          curr_access_token_user = null; // token expired
        } else {
          curr_access_token_user = decodedToken.username; // valid token
        }
      } catch (error) {
        curr_access_token_user = null; // token not in correct format
      }
    }