Skip to main content

Command Palette

Search for a command to run...

JWT Authentication in Node.js Explained Simply

Updated
3 min readView as Markdown

Introduction

Authentication is used to verify whether a user is valid or not. Whenever users log in to an application, the server checks their identity before giving access.

For example:

  • Instagram checks login details before opening the account

  • Banking apps verify users before showing account data

Without authentication, anyone could access private information.

What is JWT?

JWT stands for JSON Web Token.

It is a token-based authentication method used in modern web applications and APIs.

After successful login:

  1. The server creates a token

  2. The token is sent to the user

  3. The user sends the token with future requests

  4. The server verifies the token and allows access

JWT is mostly used because it supports stateless authentication.

What is Stateless Authentication?

In stateless authentication, the server does not store user login data.

Instead:

  • User information is stored inside the token

  • The client sends the token every time

This makes applications faster and easier to scale.

Structure of a JWT

A JWT has 3 parts:

Header.Payload.Signature

Example:

xxxxx.yyyyy.zzzzz

1. Header

The header contains information about the token type and algorithm.

Example:

{
   "alg": "HS256",
   "typ": "JWT"
}

2. Payload

The payload contains user data.

Example:

{
   "id": 101,
   "name": "Devesh"
}

This data is called claims.

3. Signature

The signature is used to verify that the token is valid and not modified.

The server checks the signature before allowing access.

Installing JWT Package

In Node.js, JWT is commonly handled using jsonwebtoken.

Install it using:

npm install jsonwebtoken

Login Flow Using JWT

Step 1: User Logs In

The user sends:

  • Email

  • Password

Step 2: Server Verifies User

If login details are correct, the server creates a token.

Step 3: Token is Sent

The token is returned to the client.

Step 4: Client Stores Token

The token is usually stored in:

  • Local storage

  • Cookies

Step 5: Token Sent with Requests

The client sends the token with future requests.

Creating a JWT Token

const jwt = require('jsonwebtoken');

const token = jwt.sign(
    { id: 101, name: "Devesh" },
    "secretKey",
    { expiresIn: '1h' }
);

console.log(token);

How This Works

jwt.sign()

Creates a token.

Payload

{ id: 101, name: "Devesh" }

Stores user information.

Secret Key

"secretKey"

Used to verify the token.

Sending Token with Requests

Tokens are usually sent inside request headers.

Example:

Authorization: Bearer your_token_here

Protecting Routes Using JWT

Protected routes only allow users with valid tokens.

Example of Protected Route

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();

function verifyToken(req, res, next) {

    const bearerHeader = req.headers['authorization'];

    if(!bearerHeader) {
        return res.send("Access Denied");
    }

    const token = bearerHeader.split(' ')[1];

    jwt.verify(token, "secretKey", (err, data) => {

        if(err) {
            return res.send("Invalid Token");
        }

        req.user = data;

        next();

    });

}

app.get('/profile', verifyToken, (req, res) => {

    res.send("Protected Profile Page");

});

app.listen(3000);

How Route Protection Works

Step 1

User sends token in request header.

Step 2

Middleware checks the token.

Step 3

If token is valid:

  • Access is allowed

If token is invalid:

  • Access is denied

Real-World Usage of JWT

JWT is commonly used in:

  • REST APIs

  • Mobile apps

  • React applications

  • Single Page Applications (SPA)

Popular platforms using token-based authentication include:

  • Google

  • Facebook

  • Netflix