If you've built any web application in the last decade, you've probably encountered JSON Web Tokens (JWT). They're everywhere—from authenticating users to securing API calls. But despite their popularity, JWTs are often misunderstood and misused, leading to security vulnerabilities that can compromise entire systems.
In this guide, we'll demystify JWTs completely. You'll learn not just what they are, buthow to use them correctly in real-world applications. For further reading, see the Auth0 documentation and Google OAuth2 documentation.
What is a JWT?
A JSON Web Token (JWT) is a compact, URL-safe way to represent claims between two parties. Think of it as a digitally signed JSON object that can be verified and trusted.
Here's what a JWT looks like in the wild:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiZW1haWwiOiJqb2huQGV4YW1wbGUuY29tIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNzA0MDY3MjAwLCJleHAiOjE3MDQxNTM2MDB9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cYes, it looks like gibberish. But those three parts separated by dots (.) contain everything needed to authenticate a user without hitting your database.
The name comes from the fact that the payload is a JSON object, it's designed for web applications, and it serves as an authentication token. The standard is defined in RFC 7519.
JWT Structure Explained
Every JWT consists of three parts, each Base64URL-encoded and separated by dots:
HEADER.PAYLOAD.SIGNATURE
xxxxx.yyyyy.zzzzzLet's decode each part to understand what's really inside.
1. Header
The header typically contains two pieces of information: the type of token and thesigning algorithm being used.
{
"alg": "HS256",
"typ": "JWT"
}Common algorithms you'll encounter:
- HS256 (HMAC-SHA256): Symmetric algorithm using a shared secret
- RS256 (RSA-SHA256): Asymmetric algorithm using public/private key pairs
- ES256 (ECDSA-SHA256): Elliptic curve algorithm, more efficient than RSA
2. Payload (Claims)
The payload contains the claims—statements about the user and additional metadata. This is where the actual data lives.
{
"sub": "user_2kX9mPqR",
"name": "Sarah Chen",
"email": "[email protected]",
"role": "admin",
"permissions": ["read", "write", "delete"],
"team_id": "team_abc123",
"iat": 1704067200,
"exp": 1704153600,
"iss": "https://auth.techcorp.com"
}There are three types of claims:
Registered Claims (Standard)
| Claim | Name | Description |
|---|---|---|
iss | Issuer | Who issued the token (e.g., your auth server) |
sub | Subject | The user ID or entity the token represents |
aud | Audience | Who the token is intended for |
exp | Expiration | When the token expires (Unix timestamp) |
iat | Issued At | When the token was created |
nbf | Not Before | Token not valid before this time |
jti | JWT ID | Unique identifier for the token |
Public Claims
Custom claims that should be registered in the IANA JSON Web Token Registry to avoid collisions. Examples: email, name, picture.
Private Claims
Custom claims agreed upon between parties. These are specific to your application:
{
"team_id": "team_abc123",
"subscription_tier": "enterprise",
"feature_flags": ["beta_dashboard", "new_api"]
}3. Signature
The signature ensures the token hasn't been tampered with. It's created by combining the encoded header, encoded payload, a secret, and the algorithm:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
your-256-bit-secret
)When your server receives a JWT, it recalculates this signature and compares it to the one in the token. If they match, the token is valid and hasn't been modified.
How JWT Authentication Works
Here's the typical flow in a web application:
User sends credentials (email/password) to your auth server
POST /api/auth/login
{
"email": "[email protected]",
"password": "••••••••"
}If credentials are valid, server generates a JWT with user claims
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 86400
}Frontend stores the JWT (typically in memory or httpOnly cookie)
Server verifies signature and checks expiration—no database lookup needed
Example Use Cases
Example 1: E-commerce Platform (Shopify-style)
An e-commerce platform needs to authenticate users and track their permissions across multiple services (storefront, admin panel, API).
// JWT Payload for a store owner
{
"sub": "user_8Kj2mNpQ",
"email": "[email protected]",
"store_id": "store_xYz789",
"role": "owner",
"permissions": [
"products:read",
"products:write",
"orders:read",
"orders:write",
"analytics:read",
"settings:write"
],
"subscription": {
"plan": "professional",
"features": ["advanced_analytics", "custom_domain", "api_access"]
},
"iat": 1704067200,
"exp": 1704153600,
"iss": "https://auth.myecommerce.com"
}Example 2: SaaS Application with Team Permissions
A project management tool like Notion or Linear where users belong to teams with different access levels.
// JWT for a team member
{
"sub": "user_4Rt6yHnM",
"name": "Alex Rivera",
"email": "[email protected]",
"organization": {
"id": "org_abc123",
"name": "TechStartup Inc",
"plan": "team"
},
"teams": [
{
"id": "team_frontend",
"role": "admin"
},
{
"id": "team_design",
"role": "member"
}
],
"feature_flags": {
"new_dashboard": true,
"ai_assistant": true,
"beta_exports": false
},
"iat": 1704067200,
"exp": 1704110400,
"iss": "https://auth.projectapp.io"
}Example 3: Microservices Communication
Internal service-to-service authentication in a microservices architecture(imagine a payment service that other internal services call).
// Service-to-service JWT
{
"sub": "service:payment-processor",
"iss": "https://internal-auth.company.com",
"aud": ["order-service", "notification-service"],
"scope": [
"payments:process",
"orders:update",
"notifications:send"
],
"service_version": "2.4.1",
"environment": "production",
"iat": 1704067200,
"exp": 1704070800,
"jti": "req_9Xk2mPqR4Hn7"
}Example 4: Mobile App with Refresh Tokens
A mobile banking app that uses short-lived access tokens with long-lived refresh tokens.
// Access Token (expires in 15 minutes)
{
"sub": "user_bank_123",
"type": "access",
"device_id": "iphone_Xk2m9Pq",
"session_id": "sess_abc123",
"permissions": ["accounts:read", "transfers:limited"],
"transfer_limit": 1000,
"iat": 1704067200,
"exp": 1704068100
}
// Refresh Token (expires in 30 days)
{
"sub": "user_bank_123",
"type": "refresh",
"device_id": "iphone_Xk2m9Pq",
"family_id": "fam_xyz789",
"iat": 1704067200,
"exp": 1706659200
}JWT vs Session-Based Authentication
One of the most common questions: "Should I use JWTs or traditional sessions?" Here's an honest comparison:
| Aspect | JWT | Sessions |
|---|---|---|
| Storage | Client-side (stateless) | Server-side (stateful) |
| Scalability | Excellent - no shared state | Requires session store (Redis) |
| Revocation | Difficult - need blocklist | Easy - delete from store |
| Size | Larger (contains all claims) | Small (just session ID) |
| Cross-domain | Easy with Authorization header | Complex (CORS, cookies) |
| Mobile/API | Ideal | Possible but awkward |
- APIs consumed by mobile apps or SPAs
- Microservices architecture
- Cross-domain authentication (SSO)
- Serverless functions
- Traditional server-rendered web apps
- When immediate revocation is critical
- Simple applications with single server
- When you need to track active sessions
Security Best Practices
1. Use Strong Secrets
// Bad - weak secret
const secret = "mysecret123";
// Good - strong random secret (256 bits minimum)
const secret = "Kx9#mP2$qR7&nL4@jH8*wF3!vB6%tY9^cZ1";
// Best - use environment variable
const secret = process.env.JWT_SECRET;2. Set Appropriate Expiration
// Access tokens: Short-lived (15 min to 1 hour)
{
"exp": Math.floor(Date.now() / 1000) + (15 * 60) // 15 minutes
}
// Refresh tokens: Longer-lived (7-30 days)
{
"exp": Math.floor(Date.now() / 1000) + (7 * 24 * 60 * 60) // 7 days
}3. Always Validate Everything
// Node.js example with jsonwebtoken (https://www.npmjs.com/package/jsonwebtoken)
const jwt = require('jsonwebtoken');
function validateToken(token) {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'], // Specify allowed algorithms
issuer: 'https://myapp.com', // Validate issuer
audience: 'my-api', // Validate audience
clockTolerance: 30 // Allow 30 seconds clock skew
});
// Additional custom validations
if (!decoded.sub) {
throw new Error('Missing subject claim');
}
return decoded;
} catch (error) {
if (error.name === 'TokenExpiredError') {
throw new Error('Token has expired');
}
throw new Error('Invalid token');
}
}4. Store Tokens Securely
Token storage is critical for security. Avoid XSS and CSRF vulnerabilities:
// Bad - localStorage (vulnerable to XSS)
localStorage.setItem('token', jwt);
// Better - httpOnly cookie (protected from XSS)
// Server sets this header:
Set-Cookie: token=eyJ...; HttpOnly; Secure; SameSite=Strict; Path=/
// Best for SPAs - keep in memory + refresh token in httpOnly cookie
class TokenManager {
private accessToken: string | null = null;
setAccessToken(token: string) {
this.accessToken = token;
}
getAccessToken() {
return this.accessToken;
}
// Refresh token is in httpOnly cookie, handled by browser
}5. Implement Token Refresh Strategy
// Frontend: Automatic token refresh
async function fetchWithAuth(url, options = {}) {
let response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${getAccessToken()}`
}
});
// If token expired, try to refresh
if (response.status === 401) {
const newToken = await refreshAccessToken();
if (newToken) {
response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': `Bearer ${newToken}`
}
});
}
}
return response;
}Common Mistakes to Avoid
Mistake #1: Storing Sensitive Data in JWT
// NEVER do this
{
"sub": "user_123",
"password": "hashed_password_here", // NO!
"ssn": "123-45-6789", // NO!
"credit_card": "4111111111111111" // ABSOLUTELY NO!
}Remember: JWTs are encoded, not encrypted. Anyone can decode and read the payload.
Mistake #2: Not Validating Algorithm
The "none" algorithm attack is a classic JWT vulnerability:
// Vulnerable to "none" algorithm attack
const decoded = jwt.verify(token, secret); // BAD
// Always specify allowed algorithms
const decoded = jwt.verify(token, secret, {
algorithms: ['HS256'] // GOOD
});Mistake #3: Using JWT for Sessions That Need Revocation
If you need to immediately invalidate a user's access (e.g., after password change or detecting fraud), pure JWTs make this difficult. Consider:
- Short expiration times (15 minutes)
- Token version in payload + check against database
- Blocklist for critical revocations
Mistake #4: Bloated Tokens
// Too much data - increases request size
{
"user": {
"id": "123",
"name": "...",
"email": "...",
"fullProfile": { /* 50+ fields */ },
"allPermissions": [ /* 100+ items */ ],
"entireOrderHistory": [ /* ... */ ]
}
}Keep tokens lean. Include only what's needed for authorization decisions. Fetch additional data from API when needed.
Mistake #5: No Expiration
// Never-expiring token = permanent security risk
{
"sub": "user_123",
"role": "admin"
// No exp claim!
}Always set expiration. Always.
Debugging JWTs
When things go wrong, here's how to debug JWT issues:
Decode Without Verification (for debugging only)
// JavaScript
function decodeJwt(token) {
const [header, payload] = token.split('.').slice(0, 2);
return {
header: JSON.parse(atob(header)),
payload: JSON.parse(atob(payload))
};
}
// Or use jwt.decode() from jsonwebtoken
const decoded = jwt.decode(token, { complete: true });
console.log(decoded.header);
console.log(decoded.payload);Check Expiration
function isTokenExpired(token) {
const { payload } = decodeJwt(token);
const now = Math.floor(Date.now() / 1000);
console.log('Token expires at:', new Date(payload.exp * 1000));
console.log('Current time:', new Date());
console.log('Expired:', payload.exp < now);
return payload.exp < now;
}Online Tools
Use jwt.io to decode and verify tokens. Just paste your token and see the decoded content instantly.
Frequently Asked Questions
Q: Can I revoke a JWT?
Not directly—JWTs are stateless by design. However, you can implement workarounds:
- Short expiration: Tokens naturally expire quickly
- Token blocklist: Store revoked token IDs in Redis
- Token version: Include version in payload, check against user record
- Refresh token rotation: Invalidate refresh token family on suspicious activity
Q: Where should I store JWTs on the client?
It depends on your threat model:
- Memory (recommended for SPAs): Most secure against XSS, but lost on refresh
- httpOnly cookie: Protected from XSS, vulnerable to CSRF (use SameSite)
- localStorage: Convenient but vulnerable to XSS—avoid for sensitive apps
Q: Should I encrypt the JWT payload?
If you need to hide the payload contents, use JWE (JSON Web Encryption) instead of JWS (JSON Web Signature). However, this adds complexity. Usually, it's better to simply not include sensitive data in the payload.
Q: What's the difference between HS256 and RS256?
HS256 (symmetric): Same secret for signing and verification. Simpler, but the secret must be shared with anyone who needs to verify tokens.
RS256 (asymmetric): Private key signs, public key verifies. Better for distributed systems—only the auth server needs the private key.
Q: How do I handle JWT in a microservices architecture?
Common pattern:
- API Gateway validates the JWT signature
- Gateway extracts user info and passes it to downstream services in headers
- Internal service-to-service calls use separate, short-lived JWTs
- Use RS256 so services only need the public key
Q: My JWT is too large. What can I do?
- Remove unnecessary claims
- Use shorter claim names (but keep standard claims standard)
- Store large data server-side, reference by ID in token
- Consider if you really need all that data in the token
Q: Can JWTs be used for anything other than authentication?
Yes! JWTs are useful for any scenario where you need to pass trusted data:
- Password reset links: Encode user ID and expiration
- Email verification: Token in verification link
- File download links: Temporary access tokens (like AWS S3 presigned URLs)
- Webhooks: Signed payloads for verification
Conclusion
JSON Web Tokens are a powerful tool for modern authentication, but they're not a silver bullet. Understanding their structure, limitations, and security implications is crucial for using them effectively.
Key takeaways:
- JWTs are signed, not encrypted—don't store secrets in them
- Always validate signatures and check expiration
- Use short expiration times with refresh token rotation
- Choose storage location based on your security requirements
- Consider whether JWTs are the right choice for your use case
Need to inspect or debug a JWT? Try our JSON Editor to decode and analyze JWT payloads easily.