parse jwt tokens in javascript

To parse a JWT token in JavaScript, you can use a library like jsonwebtoken. Here is an example of how to decode a JWT token using that library:

index.tsx
const jwt = require('jsonwebtoken');

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

const decoded = jwt.decode(token);

console.log(decoded);
270 chars
8 lines

This will output an object with the decoded token, which looks like this:

index.tsx
{
  sub: '1234567890',
  name: 'John Doe',
  iat: 1516239022
}
63 chars
6 lines

You can also verify the token using the jwt.verify method, which will throw an error if the token is invalid:

index.tsx
const jwt = require('jsonwebtoken');

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

try {
  const decoded = jwt.verify(token, 'secret');
  console.log(decoded);
} catch(error) {
  console.log(error);
}
330 chars
11 lines

gistlibby LogSnag