Decode jwt token in angular?

Published

I’ve got a requirement to decode jwt token which sent by API during login time.
How to decode jwt token in angular?

Source: Angular Questions

Published
Categorized as angular, jwt Tagged ,

Answers

I don’t think an external module is necessary to decode a JWT token. It could be done with JS atob() function.

Here is a general function using JS atob() with Array#split, Array#map and Array#reduce

function decodeToken(token) {
  const _decodeToken = (token) => {
    try {
      return JSON.parse(atob(token));
    } catch {
      return;
    }
  };
  return token
    .split('.')
    .map(token => _decodeToken(token))
    .reduce((acc, curr) => {
      if (!!curr) acc = { ...acc, ...curr };
      return acc;
    }, Object.create(null));
}

Here is a working snippet

function decodeToken(token) {
  const _decodeToken = (token) => {
    try {
      return JSON.parse(atob(token));
    } catch {
      return;
    }
  };
  return token
    .split('.')
    .map(token => _decodeToken(token))
    .reduce((acc, curr) => {
      if (!!curr) acc = { ...acc, ...curr };
      return acc;
    }, Object.create(null));
}

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

console.log(decodeToken(token));

Working example: Stackblitz


Prof. Everett Donnelly

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq