IndexedDB vs localStorage vs Cookies: When Do You Use Each?
Compare IndexedDB, localStorage, and cookies for browser storage — size limits, sync vs async, security, and when to use each.
Expected Interview Answer
Cookies are small, automatically sent-with-every-HTTP-request key-value pairs meant for server-visible state like session identifiers, localStorage is a synchronous key-value store scoped to the origin for simple client-only data, and IndexedDB is an asynchronous, transactional, indexed database built for large, structured, or queryable client-side data.
Cookies max out around 4KB per cookie and are attached to every matching HTTP request automatically, which makes them ideal for authentication tokens or session IDs the server needs to read, but wasteful and risky for large payloads since every request pays the transfer cost and exposes the data to CSRF-style concerns unless flags like HttpOnly, Secure, and SameSite are set. localStorage gives roughly 5-10MB per origin and a dead-simple synchronous string-only API, but that synchronous access blocks the main thread on large reads or writes, and there is no way to query, index, or run transactions over the data. IndexedDB removes both limits: it stores structured JavaScript objects (not just strings), supports secondary indexes for fast lookups, gives you real ACID-ish transactions, and its entire API is asynchronous so large operations never freeze the UI thread. In practice, pick cookies only for data the server must see, localStorage for small flags or preferences, and IndexedDB for offline caches, large datasets, or anything that needs querying.
- Cookies automatically travel with requests, so the server can read session state without extra client code
- localStorage offers a trivially simple synchronous API for small persisted values
- IndexedDB scales to large datasets without blocking the main thread
- IndexedDB supports indexes and transactions, enabling real querying instead of manual parsing
AI Mentor Explanation
Cookies are like the small entry wristband every spectator wears and shows automatically at every gate they pass through, so security always knows who they are without asking. localStorage is like a scorecard pinned to the pavilion wall that anyone can read or scribble on instantly, but it only holds a few lines. IndexedDB is like the full match archive room, organized by player, over, and innings, letting the statistician search and cross-reference thousands of records without ever blocking the live broadcast. Each serves a different scale of need, from tiny automatic identity to a searchable historical database.
Step-by-Step Explanation
Step 1
Identify who needs the data
If the server must read it on every request, use a cookie; if only the client needs it, use localStorage or IndexedDB.
Step 2
Estimate the data size and shape
Small flat key-value pairs fit localStorage; large, structured, or relational data needs IndexedDB.
Step 3
Consider access patterns
Synchronous, simple reads favor localStorage; async, queryable, indexed access favors IndexedDB.
Step 4
Apply security flags where relevant
Cookies holding sensitive tokens should set HttpOnly, Secure, and SameSite to limit exposure.
What Interviewer Expects
- Clear comparison of size limits, synchronicity, and transport behavior across all three
- Understanding that cookies are the only one automatically sent with HTTP requests
- Awareness that IndexedDB is asynchronous and suited to large or structured data
- Mention of security considerations for cookies (HttpOnly, Secure, SameSite)
Common Mistakes
- Storing large data or tokens in localStorage assuming it is more secure than cookies
- Using IndexedDB for a handful of trivial preference flags where localStorage would suffice
- Forgetting that localStorage access is synchronous and can block rendering on large payloads
- Not knowing cookies are sent on every matching request, inflating request size unnecessarily
Best Answer (HR Friendly)
“Cookies are small pieces of data the browser automatically sends to the server with every request, so they are great for things like login sessions. localStorage is a simple way to save small bits of data only the browser needs, like a theme preference. IndexedDB is a more powerful, database-like storage for larger or more complex data, like offline content, that will not freeze the page while it works.”
Code Example
// Cookie: server-visible, sent automatically
document.cookie = 'sessionId=abc123; Secure; SameSite=Lax; max-age=3600'
// localStorage: client-only, synchronous, small
localStorage.setItem('theme', 'dark')
const theme = localStorage.getItem('theme')
// IndexedDB: client-only, async, large/structured, queryable
const request = indexedDB.open('AppCache', 1)
request.onupgradeneeded = (event) => {
const db = event.target.result
const store = db.createObjectStore('articles', { keyPath: 'id' })
store.createIndex('byDate', 'publishedAt')
}
request.onsuccess = (event) => {
const db = event.target.result
const tx = db.transaction('articles', 'readwrite')
tx.objectStore('articles').put({ id: 1, title: 'Post', publishedAt: '2026-07-18' })
}Follow-up Questions
- How would you migrate a large localStorage payload to IndexedDB safely?
- What security risks come from storing a JWT in localStorage vs an HttpOnly cookie?
- How do IndexedDB indexes improve query performance over manually filtering an array?
- What happens to cookies, localStorage, and IndexedDB data when a user clears browsing data?
MCQ Practice
1. Which browser storage mechanism is automatically sent with every matching HTTP request?
Cookies are attached to outgoing requests automatically based on domain and path matching.
2. Why is IndexedDB preferred over localStorage for large datasets?
IndexedDB operations run asynchronously, so large reads/writes never freeze the UI thread.
3. What is a key security practice for cookies holding session tokens?
HttpOnly blocks JS access, Secure requires HTTPS, and SameSite limits cross-site sending.
Flash Cards
Which storage is auto-sent with HTTP requests? — Cookies.
Which storage is synchronous and string-only? — localStorage.
Which storage supports indexes and transactions? — IndexedDB.
Typical cookie size limit? — Around 4KB per cookie.