JSON Web Tokens Explained
JWT (JSON Web Token) is a compact, URL-safe means of representing claims between two parties. It's become the standard for API authentication.
JWT Structure
A JWT consists of three parts separated by dots:
- Header - Algorithm and token type
- Payload - Claims (data)
- Signature - Verification signature
How JWT Works
- User logs in with credentials
- Server verifies credentials and creates JWT
- Client stores JWT (usually in localStorage or httpOnly cookie)
- Client sends JWT in Authorization header for protected requests
- Server verifies JWT and processes request
Implementing JWT in Node.js
Use the jsonwebtoken library to create and verify tokens:
const jwt = require('jsonwebtoken');
// Create token
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '24h' });
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
Security Best Practices
- Use strong, random secrets
- Set appropriate expiration times
- Store secrets securely
- Implement refresh tokens for long-lived sessions
- Use HTTPS in production
- Consider token blacklisting for logout
JWT vs Session-based Authentication
JWT offers stateless authentication but comes with trade-offs in terms of token size and revocation complexity.