What is a JSON Web Token (JWT)? A Practical Guide to Using JWTs for Authentication
JSON Web Tokens are compact, URL-safe tokens used to securely transmit claims between clients and servers. In modern web development, JWTs power stateless authentication: once a user logs in, the server issues a signed token, and the client sends it with every request, eliminating server-side session storage.
Unlike opaque session IDs, JWTs are self-contained. Each token carries its own user information, permissions, and expiration time, digitally signed to prevent tampering.
Anatomy of a JWT
A JWT consists of three Base64Url-encoded parts separated by dots:
- Header: Specifies the signing algorithm (e.g., HS256) and token type.
- Payload: Contains claims like user ID, role, and expiration (
exp). - Signature: Created by hashing the header and payload with a secret key.
How JWT Authentication Works
The flow is simple. The client submits credentials to the server. On success, the server signs and returns a JWT. The client stores it and includes it in the Authorization: Bearer <token> header for subsequent API calls. The server verifies the signature and checks the expiration date before serving the request. No session lookup is required.
Using JWTs in Practice
Most frameworks offer JWT libraries. In Node.js, the jsonwebtoken package signs a token in one line:
const token = jwt.sign({ userId: 42 }, SECRET, { expiresIn: '1h' });
Then verify incoming tokens on protected routes and reject invalid or expired ones. Keep your signing secret in environment variables, prefer HTTPS, and use short expiration times to reduce risk.
JWTs are essential for scalable, stateless authentication. Master their structure, verification flow, and security best practices, and you will build more efficient APIs.