How to decode JWT in Javascript

How to decode JWT in Javascript

Decode JWT Token in JS

·

1 min read

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

You can decode JWT (JSON Web Token) by using following code.

 function parseJwt(token) {
    try {
      return JSON.parse(atob(token.split('.')[1]));
    } catch (err) {
      console.error('Error in parse JWT ', err)
      return null;
    }
  };

For example, you have a JWT like this

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6ImNmNTMxNjgxLWZkZWQtNDQ0My1hNjQ1LTQ4NThhNDQ1YzU1ZSIsImlhdCI6MTU5MDA1NTQ3NSwiZXhwIjoxNTkwMDU5MDc1fQ.H1QW0pQVfdW3nbwA-GfHGKPcu1-qyuh99UlXIEPBQJ8

Which contains this information

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "jti": "cf531681-fded-4443-a645-4858a445c55e",
  "iat": 1590055475,
  "exp": 1590059075
}

So call this function like this.

const jwtToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6ImNmNTMxNjgxLWZkZWQtNDQ0My1hNjQ1LTQ4NThhNDQ1YzU1ZSIsImlhdCI6MTU5MDA1NTQ3NSwiZXhwIjoxNTkwMDU5MDc1fQ.H1QW0pQVfdW3nbwA-GfHGKPcu1-qyuh99UlXIEPBQJ8';
const jwtTokenDetails = parseJwt(jwtToken);
console.log('JWT Token Details: ', jwtTokenDetails);