Posted on Updated on - Arjun

How to use JWT (JSON Web Token) with Express JS

Today I am gonna show you JWT(JSON Web Token) token generating and verification steps with express JS framework.

What is JWT (JSON Web Token)?

A JSON Web Token, or JWT, is used to send information that can be verified and trusted by means of a digital signature. It comprises a compact and URL-safe JSON object, which is cryptographically signed to verify its authenticity, and which can also be encrypted if the payload contains sensitive information. Because of it’s compact structure, JWT is usually used in HTTP Authorization headers or URL query parameters.

How to use JWT Express JS

Lets integrate JWT with Express JS

Create project directory and install required dependencies with below shown commands.

  • mkdir express-jwt-demo – it will crate a folder called “express-jwt-demo
  • cd express-jwt-demo – changing directory to “express-jwt-demo
  • npm init –yes – will create package.json file under the current directory
  • npm install –save express body-parser jsonwebtoken – it will download all mentioned modules into node_modules directory

What do these packages do?

  • express is the Node framework.
  • body-parser will let us pull POST content from our HTTP request.
  • jsonwebtoken is a library which will take care of generating and verifying

Now lets setup application, create a file called server.js with below code, go though the comments of the code for better understanding.

Start server and test it

Issue following command from the root of your project $ node server.js, and point your browser to http://localhost:3000.

If everything goes well you should able to see bellow output:

You can verify and decode above token, by pointing your browser with token, http://localhost:3000/verify/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFyanVucGhwQGdtYWlsLmNvbSIsImlkIjoxLCJuYW1lIjoiQXJqdW4gQSIsImlhdCI6MTQ5OTM2NjM0NH0.xRJo4je_4QIyqJpyes8ixxekTqI2EQ6v8_zW3YuG_tE

If everything goes well you should able to see bellow output:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status