Back to blog
NodeJS

JWT Authentication in Node.js Explained Simply

May 10, 2026 3 min read

What Is Authentication?

Authentication verifies who a user is.

Example:

  • Login systems

  • Admin dashboards

  • Banking apps

Without authentication:

Anyone could access protected data


Why Authentication Is Required

Applications need to:

  • Identify users

  • Protect private routes

  • Restrict access

  • Maintain login state


What Is JWT?

JWT stands for:

JSON Web Token

It is a token-based authentication system.

After login:

  1. Server creates token

  2. Client stores token

  3. Client sends token with requests

  4. Server verifies token


JWT Is Stateless

Server does not store login session data.

Instead:

Token itself contains user information

This is called:

Stateless authentication


JWT Login Flow

Diagram: sequenceDiagram

Structure of a JWT

A JWT has 3 parts:

Header.Payload.Signature


Example JWT

xxxxx.yyyyy.zzzzz


1. Header

Contains token metadata.

Example:

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


2. Payload

Contains user data.

Example:

{
  "userId": 15,
  "role": "admin"
}


3. Signature

Used to verify token authenticity.

Prevents tampering.


JWT Structure Visualization

Diagram: flowchart LR

Installing JWT Package

npm install jsonwebtoken


Creating a JWT Token

const jwt = require("jsonwebtoken");

const token = jwt.sign(
  {
    userId: 1
  },
  "secretkey",
  {
    expiresIn: "1h"
  }
);

console.log(token);


What jwt.sign() Does

PartPurpose
PayloadUser data
Secret KeyUsed for signing
expiresInToken expiry

Login Example

app.post("/login", (req, res) => {
  const user = {
    id: 1,
    email: "[email protected]"
  };

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

  res.json({ token });
});


Sending Token With Requests

Usually sent in request headers.


Authorization Header

Authorization: Bearer TOKEN_HERE


Example Request Flow

Diagram: sequenceDiagram

Protecting Routes Using JWT

Use middleware to verify token.


Example Middleware

const jwt = require("jsonwebtoken");

function verifyToken(req, res, next) {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    return res.status(401).send("Token missing");
  }

  const token = authHeader.split(" ")[1];

  try {
    const decoded = jwt.verify(token, "secretkey");

    req.user = decoded;

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


Protected Route Example

app.get("/dashboard", verifyToken, (req, res) => {
  res.send("Protected Dashboard");
});


Token Validation Lifecycle

Diagram: flowchart TD

Why JWT Is Popular

BenefitExplanation
StatelessNo server session storage
ScalableGood for APIs
Mobile FriendlyEasy token sharing
FastLightweight auth flow

Common JWT Use Cases

ApplicationUsage
REST APIsAuthentication
Mobile AppsLogin sessions
SPA AppsReact/Vue auth
MicroservicesService authentication

Common Beginner Mistakes

Storing Sensitive Data in Payload

Incorrect:

{
  "password": "123456"
}

JWT payload is readable.

Never store passwords.


Forgetting Token Verification

Creating token alone is not enough.

Always verify before allowing access.


Simple JWT Flow Summary

User Logs In
↓
Server Creates JWT
↓
Client Stores Token
↓
Client Sends Token With Requests
↓
Server Verifies Token
↓
Access Granted or Denied


Practice Example

const jwt = require("jsonwebtoken");

const token = jwt.sign(
  {
    username: "Ali"
  },
  "mysecret"
);

console.log(token);

const decoded = jwt.verify(token, "mysecret");

console.log(decoded);


Key Takeaways

ConceptSummary
AuthenticationVerifies users
JWTToken-based auth system
HeaderToken metadata
PayloadUser data
SignatureVerification mechanism
Stateless AuthNo session storage

Final Notes

JWT authentication is heavily used in modern backend systems because it works well with:

  • APIs

  • Mobile apps

  • React frontends

  • Distributed systems

Understanding JWT basics is important before learning:

  • Refresh tokens

  • OAuth

  • Access control

  • Role-based authentication


0 Comments

Sign in to join the conversation

No comments yet. Be the first to comment!