Back to Roadmap
6:00

JWT Authentication

Learn how JWT authentication works and how it is used to secure Node.js and Express.js applications

6 MIN READ VERIFIED CURRICULUM

JWT authentication is a popular method used to securely authenticate users in modern web applications.

It allows servers to verify user identity without storing session data on the server.

What is JWT?

JWT stands for JSON Web Token and is a compact, secure format used for transmitting information between parties.

JWT tokens are commonly used for authentication and authorization in APIs.

Structure of a JWT

A JWT consists of three parts separated by dots: Header, Payload, and Signature.

HEADER.PAYLOAD.SIGNATURE
text

Header

The header contains metadata about the token, such as the algorithm used for signing.

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

Payload

The payload contains user-related information called claims.

{
  "id": 1,
  "email": "john@example.com"
}
json

Signature

The signature ensures the token has not been modified.

It is created using a secret key and hashing algorithm.

Why Use JWT Authentication?

JWT authentication is stateless, scalable, and works well for REST APIs and distributed systems.

It reduces server memory usage because sessions are not stored on the backend.

Installing JWT Package

npm install jsonwebtoken
bash

Generating a JWT Token

Tokens are generated after successful user authentication.

const jwt = require('jsonwebtoken');

const token = jwt.sign(
  { id: 1, email: 'john@example.com' },
  'secretKey',
  { expiresIn: '1h' }
);
javascript

Verifying JWT Tokens

Servers verify incoming tokens before allowing access to protected routes.

jwt.verify(token, 'secretKey', (err, decoded) => {
  if (err) {
    console.log('Invalid Token');
  } else {
    console.log(decoded);
  }
});
javascript

Authentication Workflow

The user logs in using credentials, and the server generates a JWT token after successful authentication.

The client stores the token and sends it with future requests for authorization.

Sending Tokens in Requests

Authorization: Bearer TOKEN
text

Protecting Routes with Middleware

Middleware is commonly used to validate JWT tokens before granting access to routes.

const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization;

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

  next();
};
javascript

Using JWT with Express.js

app.get('/dashboard', authMiddleware, (req, res) => {
  res.send('Protected Route');
});
javascript

Token Expiration

JWT tokens often include expiration times for better security.

Expired tokens require users to log in again or refresh the token.

Refresh Tokens

Refresh tokens are used to generate new access tokens without requiring users to log in repeatedly.

Security Best Practices

Always store secret keys securely using environment variables.

Use HTTPS to protect tokens during transmission.

Hashing Passwords

Passwords should never be stored in plain text.

npm install bcrypt
bash
const bcrypt = require('bcrypt');

bcrypt.hash('password123', 10, (err, hash) => {
  console.log(hash);
});
javascript

Common Beginner Mistakes

Beginners often expose secret keys directly in source code.

Another common mistake is trusting tokens without proper verification.

Best Practices

Use short-lived access tokens and secure refresh token mechanisms.

Validate user permissions and protect sensitive API routes properly.

Real-World Importance

JWT authentication is widely used in modern web applications, mobile apps, and microservices.

Most production-level APIs rely on JWT for secure user authentication and authorization.

Summary

JWT authentication provides a secure and scalable method for handling user authentication in APIs.

Understanding JWT is essential for building secure backend systems using Node.js and Express.js.