Skip to main content

Command Palette

Search for a command to run...

How to decode JWT in Javascript

Decode JWT Token in JS

Updated
1 min read
How to decode JWT in Javascript
J

Jay Kumar is a proficient JavaScript and Node.js developer with 7 years of experience in building dynamic and scalable web applications. With a deep understanding of modern web technologies, Jay excels at creating efficient and innovative solutions. He enjoys sharing his knowledge through blogging, helping fellow developers stay updated with the latest trends and best practices in the industry.

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);
A
Anna Lena4y ago

Unfortunately atob seems to have been deprecated - or at least the version my IDE finds. I used window.atob instead.

1

More from this blog

J

JRX Codes

23 posts