Browser Storage: localStorage, Cookies, IndexedDB & Cache API
Browser storage mechanisms provide client-side persistence with distinct capacity, lifecycle, accessibility, and security characteristics: Cookies (server-sync auth), localStorage (sync key-value), IndexedDB (async structured database), and Cache API (network requests for PWAs).
Why it matters in interviews
Visual & Interactive Explanation
Client Storage Security & Architecture Comparison
HttpOnly Cookie
Authentication & Sessions
- •Immune to JavaScript XSS theft
- •Native server synchronization
- •Requires CSRF protection (SameSite / CSRF tokens)
localStorage
Synchronous Key-Value
- •Simple synchronous API
- •Persists across tabs and reboots
- •Vulnerable to XSS theft
- •Blocks main thread on large writes
IndexedDB
Async NoSQL Database
- •Huge storage capacity
- •Does not block UI thread
- •Supports indexes
- •Complex low-level API (wrap with idb/Dexie)
Code Examples & Implementation
import { openDB } from 'idb';
// Initialize asynchronous IndexedDB store
async function getDB() {
return openDB('interview-os-db', 1, {
upgrade(db) {
if (!db.objectStoreNames.contains('offline-drafts')) {
db.createObjectStore('offline-drafts', { keyPath: 'id' });
}
},
});
}
// Asynchronous write without blocking the 60fps main thread!
export async function saveDraft(id: string, content: string) {
const db = await getDB();
await db.put('offline-drafts', { id, content, updatedAt: Date.now() });
}
export async function loadDraft(id: string) {
const db = await getDB();
return await db.get('offline-drafts', id);
}Interview-Ready Answers
localStorage is synchronous 5MB key-value storage. sessionStorage clears on tab close. Cookies (4KB) are sent with HTTP requests; HttpOnly cookies protect auth tokens from XSS. IndexedDB is asynchronous, multi-gigabyte structured storage.
Official Documentation & Specifications
Follow-up Questions & Deep Dives
Common Mistakes & Anti-Patterns
- Storing JWT bearer tokens in localStorage (vulnerable to XSS script injection)
- Using synchronous localStorage for large arrays (>1MB)
- Setting SameSite=None without the Secure flag (modern browsers reject it)
Real-World Architectural Scenario
An offline note-taking app needs to store 5,000 documents with rich text attachments locally on the device. Which storage mechanism do you choose?
Rate Your Readiness
Rate how comfortably you can explain this in an interview to update your global readiness gauge: