Coder Perfect

Without utilizing a library, how can I decode a jwt token in javascript?


How can I decode the payload of JWT using JavaScript? Without a library. So the token just returns a payload object that can consumed by my front-end app.

Example token: xxxxxxxxx.XXXXXXXX.xxxxxxxx

The payload is as follows:

{exp: 10012016 name: john doe, scope:['admin']}

Asked by Chrisk8er

Solution #1

JWT parser function for unicode text:

function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);

    return JSON.parse(jsonPayload);

Answered by Peheje

Solution #2

The try-catch function is a simple function.

const parseJwt = (token) => {
  try {
    return JSON.parse(atob(token.split('.')[1]));
  } catch (e) {
    return null;


Answered by Rajan Maharjan

Solution #3

You might use jwt-decode, and then write:

import jwt_decode from 'jwt-decode';

var token = 'eyJ0eXAiO.../// jwt token';

var decoded = jwt_decode(token);
/*{exp: 10012016 name: john doe, scope:['admin']}*/

Answered by Guy

Solution #4

To decode a token into a string, use the atob() function in pure javascript:


could parse it into a json object directly:


Read about the built-in javascript functions atob() and btoa(), as well as Base64 encoding and decoding – Web APIs | MDN.

Answered by Muhammed Moussa

Solution #5

function parseJwt(token) {
  var base64Payload = token.split('.')[1];
  var payload = Buffer.from(base64Payload, 'base64');
  return JSON.parse(payload.toString());
let payload= parseJwt("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
console.log("payload:- ", payload);

If you’re using Node, you may need to utilize the buffer package:

npm install buffer
var Buffer = require('buffer/').Buffer

Answered by hashinclude72

Post is based on