2024-07-28
#browser
#storage
#cookies
#frontend
#security
Browser Storage & Sessions
Deep dive into Client-side storage: Cookies, LocalStorage, SessionStorage, and Server-side Sessions.
Cookies vs Sessions
Cookies
Small pieces of data (max 4KB) stored in the browser and sent with every HTTP request to the domain.
- Server-Side Creation: Sent via
Set-Cookieheader. - Use Cases: Authentication tokens, Language preference, Tracking IDs.
Security Flags:
- HttpOnly: Cannot be accessed via JavaScript (
document.cookie). Prevents XSS attacks stealing tokens. - Secure: Only sent over HTTPS.
- SameSite: Prevents CSRF attacks (
StrictorLax).
Sessions
Server-side storage of user state.
- User logs in.
- Server creates a Session (in memory/database) and generates a Session ID.
- Server sends Session ID to client (usually in a Cookie).
- Client sends Session ID with future requests.
- Server looks up data using the ID.
Difference:
- Cookie: Data stored on Client (sent to server).
- Session: Data stored on Server (referenced by Client).
Client-Side Storage Comparison
| Feature | Cookie | Local Storage | Session Storage |
|---|---|---|---|
| Capacity | 4KB | 5-10MB | 5MB |
| Lifespan | Manual (TTL) | Permanent (until deleted) | Tab closed |
| Scope | Sent to Server | Client Only | Client Only |
| Accessibility | Any window | Any window | Same tab |
| Use Case | Auth Tokens | App Settings, Cache | Form Data |
Local Storage
- Persistent key-value store.
- NOT sent to the server automatically.
- Synchronous (blocking) API.
- Good for: Theme preference, unsaved drafts, shopping cart (for guests).
Session Storage
- Similar to Local Storage, but cleared when the tab is closed.
- Good for: Multi-step form progress, sensitive temporary data.