Skip to main content

Command Palette

Search for a command to run...

JWT Authentication in Node.js Explained Simply

Understand how JWT works in Node.js, why it is used for authentication, and how token-based login keeps applications secure and stateless.

Updated
5 min readView as Markdown
JWT Authentication in Node.js Explained Simply

Introduction

In any web application, users need to:

  • Sign up

  • Log in

  • Access protected data

  • Stay authenticated across requests

But how does a server know who the user is after login?

That’s where authentication comes in.

Without authentication:

  • Anyone can access sensitive data

  • APIs become insecure

  • User-specific data cannot be protected

To solve this, modern applications use JWT (JSON Web Token).

What is Authentication?

Authentication is the process of verifying:

“Is this user really who they claim to be?”

Example:

  • You log in with email and password

  • Server verifies credentials

  • If correct → you get access

What is JWT?

JSON Web Token (JWT) is a compact, secure way of transmitting user information between client and server.

It is widely used in:

  • Web applications

  • Mobile apps

  • APIs

  • Microservices

JWT enables stateless authentication, meaning the server does not need to store session data.

Why JWT is Important

Traditional authentication uses sessions:

  • Server stores session data

  • Memory is used for every user

  • Harder to scale

JWT solves this by:

  • Storing data inside a token

  • No need to store sessions on server

  • Easy to scale APIs

JWT Structure

A JWT consists of three parts:

Header.Payload.Signature

Each part is encoded.

1. Header

The header contains metadata about the token.

Example:

{
  "alg": "HS256",
  "typ": "JWT"
}
  • alg → encryption algorithm

  • typ → token type

2. Payload

The payload contains user data.

Example:

{
  "id": 101,
  "name": "Rahul",
  "role": "user"
}

⚠️ Important:

  • Do NOT store sensitive data like passwords here

  • Payload is only base64 encoded, not encrypted

3. Signature

The signature ensures the token is not tampered with.

It is created using:

  • Header

  • Payload

  • Secret key

If someone changes the payload, the signature becomes invalid.

JWT Structure Diagram

Header + Payload + Signature
        ↓
     Encoded Token

JWT Login Flow

Let’s understand how authentication works step by step.

Step 1: User Login

User sends credentials:

POST /login
{
  email: "user@gmail.com",
  password: "123456"
}

Step 2: Server Validates User

  • Checks email & password

  • If correct → proceeds

Step 3: Server Generates JWT

const token = jwt.sign(
  { id: user.id, name: user.name },
  "secretKey"
);

Step 4: Token Sent to Client

{
  "token": "eyJhbGciOiJIUzI1NiIs..."
}

Step 5: Client Stores Token

Usually stored in:

  • localStorage

  • cookies

  • sessionStorage

Sending Token with Requests

When accessing protected routes:

fetch("/profile", {
  headers: {
    Authorization: "Bearer TOKEN_HERE"
  }
});

Protecting Routes Using JWT

Now the server verifies the token.

Middleware Example

const jwt = require("jsonwebtoken");

function authMiddleware(req, res, next) {

  const token = req.headers.authorization?.split(" ")[1];

  if (!token) {
    return res.status(401).send("Access Denied");
  }

  try {

    const decoded = jwt.verify(token, "secretKey");
    req.user = decoded;

    next();

  } catch (error) {
    res.status(401).send("Invalid Token");
  }
}

Using Middleware in Routes

app.get("/profile", authMiddleware, (req, res) => {

  res.send({
    message: "Protected Data",
    user: req.user
  });

});

JWT Authentication Flow

User Login
    ↓
Server Validates Credentials
    ↓
JWT Token Generated
    ↓
Token Sent to Client
    ↓
Client Stores Token
    ↓
Client Sends Token in Requests
    ↓
Server Verifies Token
    ↓
Access Granted / Denied

Stateless Authentication Concept

JWT is stateless, meaning:

  • Server does NOT store session data

  • All user info is inside token

  • Each request is independent

This makes applications:

  • Faster

  • Scalable

  • Easier to maintain

Why JWT is Popular

JWT is widely used because:

  • No session storage required

  • Works well with APIs

  • Easy to implement

  • Secure when used properly

  • Supports distributed systems

Token Validation Lifecycle

Client → Sends Token
       ↓
Server → Verifies Signature
       ↓
Valid? → Allow Access
Invalid? → Reject Request

Common Use Cases

JWT is used in:

  • Login systems

  • Role-based access control

  • APIs

  • Microservices authentication

  • Mobile apps

Security Best Practices

1. Use Strong Secret Key

"mySuperSecretKey"

2. Set Expiry Time

jwt.sign(payload, secret, { expiresIn: "1h" });

3. Do Not Store Sensitive Data

Avoid:

  • Passwords

  • Payment info

4. Use HTTPS

Prevents token interception.

Common Interview Questions

What is JWT?

A token-based authentication method for secure data exchange.

Is JWT secure?

Yes, if implemented correctly.

What happens if token is modified?

Signature validation fails and token becomes invalid.

Difference between session and JWT?

  • Session → server stores data

  • JWT → client stores token


Conclusion

JWT simplifies authentication by using a token-based stateless system.

Instead of storing sessions on the server, all necessary information is safely encoded inside a token.

With JWT, developers can build:

  • Scalable APIs

  • Secure login systems

  • Modern web applications

Understanding JWT is essential for backend development and real-world Node.js applications.