šŖ Cookies vs š Tokens ā What’s the Difference?
Both Cookies and Tokens are used for storing user authentication and session data in web applications. However, they work differently and are used in different scenarios.
š Quick Summary
Feature | Cookies | Tokens (e.g. JWT) |
---|---|---|
Storage | Stored in browser (automatically sent with requests) | Stored in localStorage or sessionStorage |
Transmission | Sent automatically with every request | Must be manually attached (e.g., in headers) |
Size Limit | ~4 KB | ~8 KB or more (but larger sizes = slower) |
Security | Vulnerable to CSRF | Vulnerable to XSS |
Usage | Traditionally for session-based auth | Used for stateless, token-based auth |
Expiration | Managed by server | Built into token payload (exp claim) |
Accessible from JS | Only if not HttpOnly | Always accessible (in local/sessionStorage) |
šŖ What Are Cookies?
Cookies are small pieces of data stored on the client-side by the browser. Theyāre used for:
Authentication
Session tracking
User preferences
Example:
Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Strict;
Automatically sent:
Every HTTP request to the same domain will include:
Cookie: session_id=abc123
ā Pros:
Automatically handled by browser
Can be
HttpOnly
(inaccessible to JS ā protects against XSS)
ā Cons:
Sent with every request (even images, scripts ā performance)
Vulnerable to CSRF (Cross-Site Request Forgery)
š What Are Tokens (e.g., JWT)?
JWT (JSON Web Tokens) are encoded strings that contain user identity and claims, usually used in stateless authentication.
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Stored manually in:
localStorage.setItem("token", jwt);
Sent in requests:
Authorization: Bearer eyJhbGciOi...
ā Pros:
Stateless (no server memory required)
Portable across services (API-friendly)
Flexible (can contain roles, permissions, etc.)
ā Cons:
Vulnerable to XSS if stored in localStorage
Can be large and slow to parse
Must be manually handled
š JWT Token Structure
A JWT has 3 parts:
[header].[payload].[signature]
Example:
{
"alg": "HS256",
"typ": "JWT"
}
.
{
"user": "john",
"role": "admin",
"exp": 1721452000
}
.
signature
āļø When to Use Cookies vs Tokens?
Scenario | Use Cookies | Use Tokens (JWT) |
---|---|---|
Traditional websites (server-rendered) | ā | Optional |
SPAs (React, Angular, etc.) | ā | ā |
Needs HttpOnly security | ā | ā |
Microservices or mobile apps | ā | ā |
Need to access data in JS | ā (unless not HttpOnly) | ā |
š Security Tips
Threat | Mitigation |
---|---|
XSS (tokens) | Use HttpOnly cookies instead of localStorage |
CSRF (cookies) | Use SameSite=Strict , CSRF tokens, or switch to tokens |
Token theft | Use HTTPS, short expiry, refresh tokens |
ā Conclusion
Want… | Use… |
---|---|
Auto-sent auth, server-side sessions | Cookies |
SPA-friendly, API-first design | Tokens (JWT) |
Max security (XSS-resistant) | HttpOnly Cookies |
Stateless microservice login | Tokens (JWT) |