Compare security profiles of localStorage, sessionStorage, httpOnly Cookies, and IndexedDB.
❓ Interview Prompt: Compare client storage mechanisms regarding XSS vulnerability, CSRF exposure, tab scoping, and secure token storage recommendations.
Evaluating client-side storage security profiles:
| Storage Mechanism | XSS Vulnerable? | CSRF Vulnerable? | Scoping & Lifetime |
|---|---|---|---|
| 'localStorage' | ❌ YES (Any JS can read) | ✅ NO (Not sent automatically) | Persistent across tabs & restarts |
| 'sessionStorage' | ❌ YES (Any JS can read) | ✅ NO (Not sent automatically) | Scoped strictly to current tab |
| 'HttpOnly' Cookie | ✅ NO (JS cannot access!) | ❌ YES (Mitigated via 'SameSite') | Sent automatically on requests |
| 'IndexedDB' | ❌ YES (Any JS can read) | ✅ NO (Not sent automatically) | Persistent structured DB storage |
Code Implementation Example
// Setting secure HttpOnly cookie response
res.cookie('jwt', token, {
httpOnly: true, // Prevents XSS script access!
secure: true, // Forces HTTPS transmission
sameSite: 'strict' // Mitigates CSRF attacks
});Store sensitive authentication tokens in HttpOnly, Secure, SameSite cookies to protect against XSS token theft.