đȘ 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) |