Script Valley
Express.js: APIs and Middleware
Authentication and AuthorizationLesson 4.1

How JWT authentication works in REST APIs

JWT structure, header payload signature, Base64 encoding, HMAC SHA256, token signing, token verification, stateless auth, Bearer token

How JWT Authentication Works

A JSON Web Token (JWT) is a compact, self-contained token with three Base64url-encoded parts separated by dots: header.payload.signature.

Header — algorithm and token type: { alg: 'HS256', typ: 'JWT' }

Payload — claims (user data): { userId: 1, role: 'admin', iat: 1700000000, exp: 1700086400 }

Signature — HMAC-SHA256 of header + payload using your secret key. Verifying the signature proves the token was not tampered with.

JWT flow in an API

// 1. User logs in → server signs a JWT
const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;

app.post('/auth/login', (req, res) => {
  const { email, password } = req.body;
  // Verify credentials (simplified)
  const user = users.find(u => u.email === email && u.password === password);
  if (!user) return res.status(401).json({ error: 'Invalid credentials' });

  const token = jwt.sign(
    { userId: user.id, role: user.role },
    SECRET,
    { expiresIn: '24h' }
  );
  res.json({ token });
});

The client stores the token and sends it with every subsequent request: Authorization: Bearer <token>. The server verifies the signature — no database lookup needed. Install: npm install jsonwebtoken.

Up next

How to write JWT authentication middleware in Express

Sign in to track progress