JSON Web Tokens from scratch — header, payload, signature, standard claims, and security best practices.
When a user logs into a website, the server needs to remember who they are for subsequent requests. The traditional solution is session cookies: the server stores session data in a database and gives the client a session ID. The problem: as your application scales to multiple servers, every server needs access to the same session database — creating a bottleneck.
JWT solves this by making authentication stateless. Instead of storing session data server-side, the server issues a token that contains the user's identity and any relevant claims. The client sends this token with every request. Any server can verify the token cryptographically without querying a database.
A JWT has three parts separated by dots:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyXzEyMyJ9.signature
Part 1 (Header): eyJhbGciOiJIUzI1NiJ9
Decoded: {"alg": "HS256", "typ": "JWT"}
Part 2 (Payload): eyJzdWIiOiJ1c2VyXzEyMyJ9
Decoded: {"sub": "user_123", "iat": 1700000000, "exp": 1700003600}
Part 3 (Signature): Verifies authenticity — cannot decode without secret key
Authorization: Bearer eyJhbG...exp claim) and other claims| Token | Typical Expiry | Purpose | Storage |
|---|---|---|---|
| Access Token | 15 minutes | Authenticate API requests | Memory (JS variable) |
| Refresh Token | 7–30 days | Get new access tokens | HttpOnly cookie |