Basics of JWT and How to Decode JWT tokens in node?

Vikash Kumar
2 min readDec 8, 2022

--

https://jwt.io

Let’s understand the structure of JWT token. JWT token consists of 3 main parts- Header, Payload and Signature. These three parts are separated by a dot(.). First part of the token is the Header, second part of the token is Payload and third part of the token is Signature(Refer left side of the snip below).

Please go to https://jwt.io/ and play with Header, Payload and Secret Code.

You’ll notice the changes in respective segment of token(left side) when you change right side.

Now let’s come to the point 😊.

We’ll create a small node project which will help us to decode the token.

  • Open an empty folder in vs code
  • Open terminal
  • Create a package.json by using “npm init
  • Include ‘jsonwebtoken’ in project by using “npm install jsonwebtoken
  • Create ‘index.js’ file
  • Import ‘jsonwebtoken’ in file: “const jwt = require(‘jsonwebtoken’)
  • Copy a token from https://jwt.io/ and store in a variable in index.js
  • There are two main methods to decode a token- decode() and verify()

decode() will help to get payload object without any verification

const jwt = require('jsonwebtoken');

const token = '' // Paste one token here

console.log(jwt.decode(token)); // Log payload object in terminal

Now run node .\index.js in terminal and see the output.

verify(token, secret) requires two argument- token and secret key

Let’s create a token with some customized secret key. You can store that secret key in a constant.

const jwt = require('jsonwebtoken');

const secretKey = `Let's Rock`; // Using this as a secret key
const token = '' // paste token here

console.log(jwt.verify(token,secretKey)); // Log payload object in terminal

Let’s again run node .\index.js in terminal and see the output.

If you try to use verify() without secret key then It will throw JsonWebTokenError

Thank you for reading this article.

HAPPY LEARNING

--

--