JWT Basics
JSON Web Tokens (JWTs) are a popular way to implement stateless authentication. Let's understand how they work.
What is a JWT?
A JWT is a self-contained token that includes:
- Identity information (who)
- Permissions (what they can do)
- Expiration time
- Cryptographic signature
JWT Structure
A JWT has three parts separated by dots:
xxxxx.yyyyy.zzzzz
│ │ │
│ │ └── Signature
│ └── Payload
└── Header
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4iLCJpYXQiOjE1MTYyMzkwMjJ9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Header
Algorithm and token type (Base64 encoded):
{
"alg": "HS256",
"typ": "JWT"
}
Payload
Claims about the user (Base64 encoded):
{
"sub": "user_123",
"name": "Alice Smith",
"role": "admin",
"iat": 1704067200,
"exp": 1704070800
}
Signature
Verifies the token hasn't been tampered with:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Standard Claims
| Claim | Name | Description |
|---|---|---|
sub | Subject | User ID |
iat | Issued At | When token was created |
exp | Expiration | When token expires |
iss | Issuer | Who issued the token |
aud | Audience | Who the token is for |
jti | JWT ID | Unique token identifier |
Exercise: Decode a JWT
Loading JavaScript Exercise...
JWT Authentication Flow
1. User logs in with credentials
POST /auth/login { email, password }
2. Server validates and creates JWT
← 200 OK { token: "eyJ..." }
3. Client stores token
localStorage.setItem('token', token)
4. Client sends token with requests
GET /api/users
Authorization: Bearer eyJ...
5. Server validates JWT and processes request
← 200 OK { users: [...] }
JWT Best Practices
1. Use Short Expiration
{
"exp": 1704070800 // 15 minutes to 1 hour
}
2. Implement Refresh Tokens
- Access token: short-lived (15 min)
- Refresh token: long-lived (7 days)
3. Don't Store Sensitive Data
JWTs are encoded, not encrypted. Anyone can decode them.
4. Use Strong Secrets
// Bad
const secret = 'password123';
// Good
const secret = crypto.randomBytes(64).toString('hex');
5. Validate All Claims
if (payload.exp < Date.now() / 1000) {
throw new Error('Token expired');
}
if (payload.iss !== 'my-api') {
throw new Error('Invalid issuer');
}
JWT vs Sessions
| Feature | JWT | Sessions |
|---|---|---|
| Storage | Client | Server |
| Scalability | High | Requires shared store |
| Revocation | Difficult | Easy |
| Size | Larger | Small ID |
| Stateless | Yes | No |
Summary
JWTs are:
- Self-contained tokens with user information
- Signed to prevent tampering
- Stateless (no server storage needed)
- Should be short-lived with refresh tokens

