Skip to main content

Command Palette

Search for a command to run...

JWT Authentication in Node.js Explained Simply

Published
3 min read

Why Authentication is Required

Before diving into JWT, let’s understand the core problem.

When a user interacts with your application (login, profile, payments), your server needs to answer:

👉 “Who is this user?”

Without authentication:

  • Anyone can access protected data

  • No user-specific experience

  • Security risks increase drastically

Authentication ensures:

  • Only valid users can access resources

  • Actions are tied to identities

  • Sensitive data remains protected


What is Authentication?

Authentication is the process of verifying who a user is.

Example:

  • You log in using email & password

  • Server checks credentials

  • If valid → user is authenticated


What is JWT?

JWT (JSON Web Token) is a compact, secure way to transmit user identity between client and server.

👉 Instead of storing session data on the server, JWT allows stateless authentication.

Stateless Authentication (Simple Explanation)

  • Server does not store user session

  • All required user info is stored inside the token

  • Every request carries that token

This makes systems:

  • Scalable

  • Faster (no DB lookup for session)

  • Ideal for APIs


Structure of a JWT

A JWT consists of 3 parts, separated by dots:

xxxxx.yyyyy.zzzzz

1. Header

Image Image

The header contains metadata about the token.

Example:

{
  "alg": "HS256",
  "typ": "JWT"
}
  • alg → algorithm used for signing

  • typ → token type


2. Payload

Image

This contains the actual data (called claims).

Example:

{
  "userId": "12345",
  "email": "user@example.com"
}

Types of claims:

  • Registeredexp, iat

  • Public → custom data

  • Private → app-specific

⚠️ Important: Payload is not encrypted, only encoded.


3. Signature

Image Image

The signature ensures the token is not tampered with.

Created using:

Header + Payload + Secret Key

If someone modifies the token → signature becomes invalid.


Login Flow Using JWT

Image Image

Here’s how JWT-based login works:

  1. User sends login request (email + password)

  2. Server verifies credentials

  3. Server generates JWT

  4. Token is sent back to client

  5. Client stores token (localStorage/cookie)


Sending Token with Requests

After login, every request must include the token.

Common method:

Authorization: Bearer <token>

Example in fetch:

fetch('/profile', {
  headers: {
    Authorization: `Bearer ${token}`
  }
})

Protecting Routes Using JWT

On protected routes:

  1. Server reads token from request header

  2. Verifies token using secret key

  3. Extracts user data

  4. Allows or denies access

Example (Express middleware):

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, 'SECRET_KEY');
    req.user = decoded;
    next();
  } catch (err) {
    res.status(400).send('Invalid Token');
  }
}

Key Takeaways

  • Authentication = verifying user identity

  • JWT enables stateless authentication

  • Token has 3 parts: Header, Payload, Signature

  • No server-side session storage required

  • Token must be sent with every request

  • Middleware protects routes


Final Insight

JWT is powerful, but use it correctly:

  • Always set expiration (exp)

  • Never store sensitive data in payload

  • Keep your secret key secure