Hey there, In this article, we would be learning how to implement authentication in nodejs using express and JWT aka JSON web tokens
What are JSON web tokens?
JSON web tokens or JWT is a simple long string that contains some data in an encoded way. Sounds confusing? here is an example
A Sample JWT String may look like:
Now, Let’s decode the above JWT string
You can decode the string by visiting https://jwt.io/ and paste the above string into the debugger present on the mentioned link.
"name": "Piyush Garg",
So, I hope that now you have a simple idea that what JSON web tokens are!
Now, with that being set let’s create an express application and implement authentication with JWT
I’ll be guiding you step by step and I would highly recommend you to code along with me.
Step 0: Creating a boilerplate code.
A very basic express starter code. We would be protecting the ‘/profile’ route so that only logged in users can access that route.
Step 1: Installing Dependencies
For this project, we would be installing a few dependencies.
Run the following command in your terminal or command prompt:
npm install express jsonwebtoken cookie-parser
Step 2: Creating Middleware functions to deal with tokens
In this step, we would be creating functions which would be used as middlewares to protect our certain routes.
Trust me it’s really simple 😉
So, Create a new .js file in your project directory. Lets call it as auth.js. In this file, we would be creating functions that we need to deal with tokens.
Great going, Now let’s create a couple of functions
- generateToken(): This function would take data as a parameter and return the token after generating it.
- isLoggedIn(): This function is responsible for checking if the current user is logged in or not.
Yeah! That’s it. Lets Codeee 🤟🏻
In auth.js we have created two functions as mentioned above. Please go through the code and you would understand the flow behind it.
Yep, that’s it. Now let’s protect our routes
Back to index.js let’s create two routes signup route and login route.
In this article, I’ll be coding only the signup route.
Your assignment is to create the login route
Step 3: let’s protect our route
To protect your route, just call the isLoggedIn function as middleware before the route that you want to protect and that’s it.
Updated profile route:
req.user holds the current user which is logged in. Navigate to auth.js line number 18:
req.user = decoded;
This is where we set the value of req.user to the current user.
Value of req.user is exactly the same as we defined the payload while generating the token.