Skip to main content

Command Palette

Search for a command to run...

JWT Authentication in Node.js Explained Simply

Updated
3 min read
JWT Authentication in Node.js Explained Simply

In today’s digital world, most websites and applications require users to log in before accessing their personal data. This process is called authentication. Whether you are using social media, online banking, or shopping websites, authentication ensures that only the correct user can access their account.

1. What is Authentication?

Authentication means verifying the identity of a user.

For example:

  • Entering username and password

  • Using OTP (One-Time Password)

  • Biometric methods like fingerprint

The main purpose is to make sure that the user is who, they claim to be.

Why Authentication is Required

Authentication is important because:

  • It protects user data

  • Prevents unauthorized access

  • Maintains privacy and security

Without authentication, anyone could access sensitive information, which can be dangerous.


2. What is JWT?

JWT stands for JSON Web Token.

It is a method used for authentication where the server sends a token to the client after login. The client stores this token and uses it for future requests.

This is called stateless authentication:

  • The server does not store user session data

  • All necessary information is present inside the token

This makes the system faster and more scalable.

  • No need to store sessions on server

  • Fast and efficient

  • Works well with APIs

  • Easy to scale

Important Tips

  • Do not store sensitive data in payload

  • Always use strong secret keys

  • Use HTTPS for secure communication


3. Structure of a JWT

A JWT has three parts:

Header.Payload.Signature

1. Header

The header contains information about the token type and algorithm used.

Example:

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

2. Payload

The payload contains user data (called claims).

Example:

{
  "userId": 1,
  "name": "Rahul"
}

This data is encoded, not encrypted.

3. Signature

The signature is used to:

  • Verify that the token is valid

  • Ensure that data has not been changed


4. JWT Login Flow

User enters login details 
          ↓ 
Server verifies credentials 
          ↓ 
Server generates JWT 
          ↓ 
Token sent to client 
          ↓ 
Client stores token 
(browser/localStorage)

Token Validation Lifecycle

Client sends request with token 
           ↓ 
Server receives token 
           ↓ 
  Token is verified 
           ↓ 
       If valid → access granted 
       If invalid → access denied

5. Sending Token with Requests

After login, the client must send the token with every request.

Example:

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

The token is usually sent in the Authorization header.


6. Protecting Routes Using Tokens

Some routes should only be accessed by logged-in users. These are called protected routes.

Example (Express Middleware):

import jwt from 'jsonwebtoken';

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

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

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

  try {
    const user = jwt.verify(token, "secretKey");
    req.user = user;
    next();
  } 
  catch (err) {
    res.send("Invalid Token");
  }
}

Protected Route Example:

app.get("/dashboard", isLoggedIn, (req, res) => {
  res.send("Welcome to dashboard");
});

Only users with valid tokens can access this route.

Conclusion

JWT is a simple and powerful way to handle authentication in modern applications. It allows secure communication between client and server using tokens instead of storing session data.

JWT makes authentication easy, fast, and scalable, which is why it is widely used in web development today.