Skip to main content

Command Palette

Search for a command to run...

JWT Authentication in Node.js Explained Simply

Updated
4 min read
JWT Authentication in Node.js Explained Simply
S

Learning web development in public. Writing simple, real-world explanations about web development concepts. Helping beginners understand why things work, not just how.

When building real-world applications, one of the most important features is authentication. You need a way to verify who the user is before giving access to protected data.

In this blog, you will understand what authentication is, what JWT is, and how it works in a simple and practical way.


1. What Authentication Means

Authentication is the process of verifying a user’s identity.

In simple terms:

  • User provides credentials (like email and password)

  • Server checks if they are correct

  • If valid, the user is allowed to access the system

Example:

  • Logging into a website

  • Accessing your profile

  • Making a secure API request

Without authentication, any user could access any data, which is not safe.


2. What JWT is

JWT stands for JSON Web Token.

It is a compact, secure way of transmitting information between client and server.

Instead of storing session data on the server, JWT allows the server to send a token to the client. The client then sends this token with every request.

This makes the system stateless, meaning:

  • Server does not need to remember user sessions

  • Each request carries its own authentication data


3. Structure of a JWT

A JWT consists of three parts separated by dots:

Header.Payload.Signature

Each part has a specific purpose.


a) Header

The header contains metadata about the token.

Example:

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

  • typ → token type


b) Payload

The payload contains the actual data (claims).

Example:

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

This data is encoded but not encrypted, so it should not contain sensitive information like passwords.


c) Signature

The signature ensures that the token is secure and not tampered with.

It is created using:

  • Header

  • Payload

  • Secret key

Example concept:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

If someone tries to change the payload, the signature will not match.


4. Login Flow Using JWT

Let’s understand how JWT works during login.

Step-by-step flow:

  1. User sends login request (email + password)

  2. Server verifies credentials

  3. If valid, server creates a JWT token

  4. Token is sent back to the client

  5. Client stores the token (localStorage, cookies, etc.)

Example (Node.js with Express):

const jwt = require('jsonwebtoken');

app.post('/login', (req, res) => {
  const { email, password } = req.body;

  // assume user is valid
  const token = jwt.sign(
    { email: email },
    'secretKey', // remember to store it in .env 
    { expiresIn: '1h' }
  );

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

5. Sending Token with Requests

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

Usually, the token is sent in the Authorization header:

Authorization: Bearer <token>

Example request:

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

This allows the server to identify the user making the request.


6. Protecting Routes Using Tokens

To protect routes, the server verifies the token before allowing access.

Example middleware:

const jwt = require('jsonwebtoken');

function authenticate(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 (err) {
    res.status(403).send('Invalid token');
  }
}

Using middleware:

app.get('/profile', authenticate, (req, res) => {
  res.send(`Welcome ${req.user.email}`);
});

Only users with a valid token can access this route.


Final Understanding

  • Authentication verifies user identity

  • JWT is a token-based authentication method

  • It contains Header, Payload, and Signature

  • Server generates token after login

  • Client sends token with every request

  • Protected routes verify the token before access


Summary

JWT provides a simple and scalable way to handle authentication in Node.js applications. Instead of maintaining sessions on the server, all necessary information is stored inside the token itself. This makes the system stateless and efficient. By understanding how tokens are generated, sent, and verified, you can build secure APIs and protect sensitive routes in your application. JWT is widely used in modern web development and is an essential concept for building real-world backend systems.