Node.js › Authentication & Authorization

What is a JSON Web Token (JWT), and what are its three parts?

Intermediate

Answer

A JWT is a compact, self-contained, digitally signed token used to represent claims (like a user's identity and permissions) that can be verified without needing a server-side lookup, unlike a session ID. It consists of three base64url-encoded, dot-separated parts: a header (specifying the signing algorithm and token type), a payload (the actual claims, like userId and role), and a signature (computed over the header and payload using a secret or private key, allowing the server to verify the token hasn't been tampered with).
const jwt = require('jsonwebtoken');

const token = jwt.sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });

// Verifying an incoming token
try {
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  req.user = decoded;
} catch (err) {
  return res.status(401).json({ error: 'Invalid or expired token' });
}
Real-world example A mobile app authenticates once against an API and stores the returned JWT locally, attaching it as a Bearer token on every subsequent request, letting the API verify the user's identity statelessly on each server instance without needing a shared session store at all.

Common follow-ups: Why is it critical to never store sensitive data like a password inside a JWT's payload, given the payload is only encoded, not encrypted?;How do you handle revoking a JWT before its natural expiration, given it's normally self-contained and stateless?