Authentication in express with JWT in 2 min

Dikshant Rajput
2 min readSep 18, 2022

Authentication is one of the most important things for an application and JWT has become one of the best standards to make it possible.

Authenticating is the process of determining who the user is. Every website or application has some sort of user involved and getting the logged-in user is one of the common things you would be doing while developing APIs or servers. In express, implementing JWT token authentication is just like a piece of cake. So without wasting any time let’s get started.

In my previous articles, I discussed about setting up a server and adding middleware in Express. We will be using the reference from there for setting up middleware and server.

We will be using jsonwebtoken npm package. So let’s install the package by running:

npm i jsonwebtoken

We will generate a token if user logs in with correct credentials. generating is also known as signing a token. Signing a token is done by just using sign() method of jsonwebtoken package

This will generate a token and send it as a response.

To verify this token, we will be using the .verify() method in our middleware

This middleware will verify the token and pass on the user to the request via the auth property. In every protected route, the user will be extracted from req.auth.user property. An example of protected route with user will look something like this:

Use the user property everywhere required in your application. That’s it, you have protected your application routes with the JWT token authentication mechanism.

I hope you like the blog and if you do, don't forget to hit the clap icon and follow me for more such blogs.

Drink water. Keep smiling…

--

--