3rd March 2022

JWT authentication in NodeJs

Build React Application

What is JWT?

JSON Web Token is an open standard for securely transferring data within Client using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server.

In this tutorial we are going to add JWT as middleware to protect our API from UnAuthorized access.

Create a New Directory

Let's create a new directory named 'NodeWithJwt' and navigate to that Directory using the following commands

mkdir NodeWithJwt
cd NodeWithJwt

After Creating the new Directory Use the Following Command to generate a new package.json file which will contain all the required meta data.

npm init

Now to run the node application we need to install express framework which will help us to serve the application

npm install express

Now lets add Express layer to our Nodejs application

Open the folder in text-editor of your choice. Here I've used Visual Studio Code.
And create a file named index.js in the directory root.
In that file paste the following code which uses 'express' to serve the application in the port 6000

const express = require('express');
  const app = express();
  const port = 6000;
  app.get('/get', (req, res) => { 
      res.send("Hello world");
  app.listen(port, () => {
      console.log('Server is running at port ${port}');

Now we will test our NodeJs application.
Use the following command in command prompt to run the application

>node index.js

Next To use Jwt Token we need to install jsonwebtoken Module. Use this command to install it.

>npm i jsonwebtoken

Next in index.js file add a new Method named generateJwtToken. This method will generate our Jwt Token.

    let token = jwt.sign({ Username: 'Tech'}, 'YourSecretkey', {
        expiresIn: '10h'

Let's test this using Postman. We can see that we can that JWT token is generated.


Next, we will use the JWT token to authorize our request. Before that let's add a method which expects JWT token in the request, only if the JWT token is valid then the method will be accessed.

app.get('/getWithAuthorization',isAuthorized, (req, res) => {
    res.send("AUTHORIZED Hello world");

function isAuthorized(request, response, next) {
    if (typeof request.headers.authorization !== "undefined") {
        let token = request.headers.authorization.split("Bearer")[1].trim();

        jwt.verify(token, 'YourSecretkey', (err, user) => {

            if (err) {
                return response.status(401).json({ error: "Not Authorized" });
            return next();
    else {
        return response.status(401).json({ error: "Not Authorized" });

The above method will be hit only if a valid JWT token is sent.

If we remove the JWT token from the header then we will get 401 UnAuthorized error


Hence, we have added JWT in our application as middleware to protect our API from UnAuthorized access.

About Us

VS Online Services : Custom Software Development

VS Online Services has been providing custom software development for clients across the globe for many years – especially custom ERP, custom CRM, Innovative Real Estate Solution, Trading Solution, Integration Projects, Business Analytics and our own hyperlocal e-commerce platform vBuy.in and vsEcom.

We have worked with multiple customers to offer customized solutions for both technical and no technical companies. We work closely with the stake holders and provide the best possible result with 100% successful completion To learn more about VS Online Services Custom Software Development Solutions or our product vsEcom please visit our SaaS page, Web App Page, Mobile App Page to know about the solution provided. Have an idea or requirement for digital transformation? please write to us at siva@vsonlineservices.com

Let's develop your ideas into reality