JSON Web Token (JWT) Implementation with node JS with MySQL or MongoDB

Nishanthan Janarthanarajah
10 min readMay 2, 2021

In this article, we are going to see the basic implementation of JSON Web Tokens (JWT) using node JS. We are going to create an API where we can register a user, then login to the system and then create a new post. To get the maximum use of this article, you must need at least the basic knowledge of JavaScript and node JS.

I have explained easy as possible for any kind of readers. If you already have knowledge about the what is JWT and the uses and structure of it, please skip to the implementation

What is a JSON Web Token (JWT)?

JWT is a term that defines for securely transmitting information between parties as a JSON object. For example, imagine when you go to a adventure park, at the entrance of the park, security will give you a token after your payment so that the token is the evidence that you are accessed inside the park. And that token will contain a serial key which is encrypted and it contains your details in it. So that when ever security decrypt it , he can read your details in it and give you access to use all the things in the park.

Just the like the above example, JWT is a token which will be created using the user’s details whenever the user tries to login. If the login details are correct, the token will be created with some secret keys and with the user details and it will be encrypted and form a token in a string format.

eyJhbGciOiJIUszI1NiIsInR5cCI6IkpXVCJ9.eyJpeZCI6IjYwOGUzNjhthYTcyMTk4NTEwNGJlNjU5YiIsImflhdCI6MTYxOTkzdsdsMjgyN30.WFX9TVC7wTVlztDHoipBRcCSZU4RXsnYFMb7pZL1YPk

The above string is the example of a token which will be returned when you login to a system. This token is the evidence for your successful login. Whenever you try to do an activity in the system (i.e. make a booking), the system expects to see your token to verify your access, and when you provide the token in the request header, the system will verify the token and allow you to access the desire function.

When should we use JSON Web Tokens(JWT)?

The main two uses of the JWT are for authorization and data/ information exchange. Authorization is after user log in, having the access to access the secure routes. and the data/information exchange is securely transmitting the user details in an encrypted form.

What is the JSON Web Token structure look like?

The JWT can be separated in three parts and these three parts are separated by dots(.) , see the above token example :

Header : The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

payload : payload consist of private details of the user

signature: To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

Putting all together, forms the JWT Token. You can see a visual example in the below image.

parts of JWT token explained

Implementation example of the JWT

To start the implementation, you need to have node JS and VS code installed in your machine.

First of all create a new node JS project by the giving the below command.

npm init

This command will help to set up a new npm package, and create a file called package.json.

Then you need to install certain set of dependencies which will be require for building this project. To install those dependencies run the below command.

yarn add bcrypt dotenv express joi jsonwebtoken mongoose mysql nodemon

This command will install all these packages and create a node_modules folder.

Then in the package JSON, change the start property in the script object as below

“scripts”: {

“start”: “nodemon src/index.js”

}

Make sure your main file (index.js) path is correct after the nodemon in the above example. This tells the node JS that the index JS is the main file and when you run yarn start or npm start , it will trigger the nodemon and nodemon will trigger the above mention index JS page.

What is nodemon?

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

So finally your package JSON will look like this:

package.json

And make sure the your dependencies are correct as in the example.

Now to test everything is configured correctly. populate your main JS(index JS or whatever file you have mentioned in scripts object and in start property in package Json) as below.

test the configuration

so when you run yarn start and when you open the chrome and check the http://localhost:3000/ , the output will be

output in the browser

If you have had come to this stage congratulation, you have set up the basic node JS project which successfully runs on port 3000. Now we will see the further implementation.

Now we will create a authentication Routes. so we create a page called authRoute.js and populate it with below code.

authRoute.js

and then in index JS, import the above page as shown in below.

now when you run the application, and when you go to http://localhost:3000/api/user/register in postman, you are going to see something like below.

post man

Now, we implement the real register function. To do that we need to have the Mongo DB or the MySQL connection. The below code shows the example of implementation of both MySql and Mongo DB.

mongo db
mysql

and the dotenv file (.env) which holds the all the variables will look like

.env

Now we can import the your database connection in the index JS and get the successful connection as below:

const mongoConnection = require(‘./connection/mongodb’)

and call the mongo db function like this in index JS:

index. js

now save the changes and run the application. In the if the mongo db credential are correct and if DB connection is successful , your console log will look like below:

terminal

Congratulations buddy. You have successfully connected to your mongo DB. If you don’t know how to create a mongo DB please click here.

Now we create the User schema to register users in the database. Create a new file called users.js and populate your file with the below code.

users.js

The salt in the above code is a security hashed password. It is needed to create the JWT token. To learn more about it, please visit here. now it is good practice to do a validation for the data we send to the database according to the above schema properties in the user.js (i.e.: email property in the user schema must me in email format). The Joi package is going to help us do the validation. To learn more about the Joi, visit here.

The below code shows, how to do the validation as per the properties in the user schema in the users.js shown below. Create a file call validation.js and populate the file with below code:

validation.js

This contains the validation for both register and login schemas.

Now we implement the login and register function. Now populate the auth route like this to do the login and register.

authRoute.js

Run the application and check the functions in the postman. If everything works fine, You will get the response as below:

postman

Now the register User is successful. Now we have come to the main part. Creating token when there is a successful login. Now implement creating token and logging in to the system.

In the authRoute.js populate the login and register route with the below code:

register route
authRoute.js

In the above function,

this block code we are creating the token with the Secret key we provided in the .env file and with the id of the user. Now we will check the login in the postman and check the reuslts:

login response

If you get the token as return , Congratulations!!!!!!!!!! you have successfully created the JWT implementation.

Now we have a token in return after login, but is that enough? No right. We also need to verify the token to allow access the secure routes. So we implement the method to verify the token, create a file called verifyToken.js as shown below:

verifyToken.Js

Here we are verifying the jwt token.

Now we create a method to create a post, with secure routes. We can only create posts, only if we are logged in.

As we created a user schema. we have to create a post schema.

post.js

Now we create a post route and import this schema in that route and create a create post function.

before that, we have to import the verifyToken created above to make the route secure. so we can import the verifyToken function like below in postRoute page we are going to create to make the route secure.

Now after importing it, we can populate the postRoute.js like this

postRoute.js

In the above implementation, we are making the create and get routes of posts secure by

router.post(“/post”,verify, async (req, res) => {

After the route path and before the callback function we are providing the verify Token function and making the route secure..

Now we save the changes and run the application and see the results in postman.

So now we run the create new post request without providing the token in the header, that means we are going to try to create a new post without logging in.

without logging in

We got the respond as access Denied, because we did provide the token in the header that we got after logging into the system. So now we understand that the system didn’t allow us to create post without logging into the system.

Now we provide the token in the header and try to create the new post.(which means, we gonna log in and then create the new post ). So we give the token in the request header like this:

giving token in the request header

now we have given the token in the request header, which means we are successfully logged in to the system. Now we try creating the new post:

created a new post

Now if you get this kind of response, CONGRATULATIONS!!!!!!!!!!!!!!!!!!!!!!!!

You have successfully implemented JWT tokens and created secure routes.

If you find errors while you run, please debug the code and try find the mistakes….

This is the very basic backend API we implement JWT token and do secure routes.

Find the code base for this implementation in my github.

IF THIS ARTICLE IS USEFUL TO YOU, PLEASE SHARE WTH YOUR FRIENDS AND SHARE YOUR KNOWLEDGE

KEEP LEARNING KEEP UPDATING KEEP CODING…………………………..

…………………………….……..HAPPY CODING …………………………….

--

--