A JSON Web Token is a compact, self-contained token format for securely transmitting claims between parties. JWTs are commonly used for authentication: after login, the server issues a token that the client sends with subsequent requests to prove identity. The token itself contains the user's identity and permissions, eliminating the need for server-side session storage.
How It Works
A JWT has three parts separated by dots: header, payload, and signature. The header specifies the signing algorithm (HS256, RS256). The payload contains claims, which are standardized fields like sub (subject/user ID), exp (expiration time), iat (issued at), plus custom claims like role: "admin". The signature is created by signing the header and payload with a secret key.
The resulting token looks like: eyJhbGciOi...eyJzdWIiOi...SflKxwRJSM.... Anyone can decode and read the payload (it is base64-encoded, not encrypted), but nobody can modify it without invalidating the signature. The server verifies authenticity by recalculating the signature with its secret key.
Why It Matters
JWTs enable stateless authentication. Traditional session-based auth stores session data on the server and requires database lookups on every request. JWTs are self-contained, so the token itself carries all needed information. This simplifies horizontal scaling because any server instance can verify a token without shared session storage.
JWTs also work across services. A token issued by your auth service can be verified by your API gateway, microservices, and third-party integrations without those services contacting the auth server.
In Practice
A user logs into a Next.js application. The server verifies credentials, generates a JWT with the user's ID and role, and returns it. The client stores the token (typically in an httpOnly cookie) and sends it with every API request. The API middleware verifies the signature and expiration before processing the request.
Common Mistakes
Never store sensitive data in JWT payloads because they are readable by anyone. Always set short expiration times (15-60 minutes) and use refresh tokens for extended sessions. Never use the none algorithm in production. Store tokens in httpOnly, Secure, SameSite cookies rather than localStorage (vulnerable to XSS). Implement token revocation for logout and compromised accounts despite JWTs being stateless.