Browser Storage Interview Questions: Cookies vs localStorage vs sessionStorage vs IndexedDB
12 browser storage interview questions with code: cookies vs localStorage vs sessionStorage, cookie attributes (HttpOnly, Secure, SameSite, Domain, Path, Max-Age), storing objects, the storage event, IndexedDB, the Cache API, storage limits and eviction, third-party cookies and privacy.
Every web app stores something in the browser: a session, a theme preference, a draft, offline data. Interviewers ask about browser storage to check that you pick the right option and understand its security and lifetime trade-offs. Here are 12 browser storage interview questions with answers and code.
Comparing the options#
Q1. What is the difference between cookies, localStorage and sessionStorage?#
| Cookies | localStorage | sessionStorage | |
|---|---|---|---|
| Capacity | About 4KB per cookie | About 5MB per origin | About 5MB per origin |
| Sent to server | Automatically with every matching request | Never | Never |
| Lifetime | Until Expires/Max-Age, or session if not set | Until cleared | Until the tab or window closes |
| Scope | Domain and path (can include subdomains) | Origin, shared across tabs | Origin and the individual tab |
| Readable by JS | Yes, unless HttpOnly | Yes | Yes |
| API | document.cookie string, Set-Cookie header | Synchronous key/value | Synchronous key/value |
Rule of thumb: cookies for data the server needs (sessions), localStorage for small, non-sensitive client preferences, sessionStorage for per-tab temporary state, and IndexedDB for large or structured data.
Q2. How do you use localStorage and sessionStorage? How do you store objects?#
// Strings only: serialise objects with JSON
const settings = { theme: "dark", fontSize: 16 };
localStorage.setItem("settings", JSON.stringify(settings));
function readSettings() {
try {
return JSON.parse(localStorage.getItem("settings")) ?? { theme: "light" };
} catch {
return { theme: "light" }; // corrupted value or storage blocked
}
}
localStorage.removeItem("settings");
sessionStorage.setItem("checkoutStep", "2");
localStorage.clear(); // removes everything for this originGotchas: values are always strings (setItem("count", 5) stores "5"); getItem returns null for missing keys; access can throw in some private modes, when storage is disabled or when the quota is full, so wrap it in try/catch. The API is synchronous and blocks the main thread, so avoid storing large data.
Q3. Does sessionStorage survive a page refresh? What about new tabs?#
Answer: sessionStorage survives reloads and back/forward navigation in the same tab. It's cleared when the tab closes. Opening a link in a new tab gives that tab a fresh copy of the original tab's sessionStorage at that moment (in most browsers), after which they're independent. Two tabs opened separately to the same site never share sessionStorage, while they do share localStorage.
Cookies#
Q4. Explain the important cookie attributes#
Set-Cookie: sid=9f8a7b; Max-Age=3600; Path=/; Domain=example.com; Secure; HttpOnly; SameSite=Lax| Attribute | Effect |
|---|---|
Expires / Max-Age | When the cookie expires; without them it's a session cookie |
Domain | Which hosts receive it; setting it includes subdomains, omitting it means the exact host only |
Path | URL path prefix that receives it |
Secure | Only sent over HTTPS |
HttpOnly | Not accessible from JavaScript (document.cookie), protecting it from XSS theft |
SameSite | Strict, Lax (default) or None (requires Secure): controls sending on cross-site requests, protecting against CSRF |
Prefixes add guarantees: a cookie named __Host-sid must be Secure, have Path=/ and no Domain, so it's locked to one host.
Q5. How do you read and write cookies in JavaScript?#
// Write (one cookie per assignment; it doesn't overwrite others)
document.cookie = "lang=hi; Max-Age=31536000; Path=/; SameSite=Lax; Secure";
// Read: one string of "name=value" pairs
function getCookie(name) {
return document.cookie
.split("; ")
.find((row) => row.startsWith(name + "="))
?.split("=")[1];
}
// Delete: set an expiry in the past with the same Path/Domain
document.cookie = "lang=; Max-Age=0; Path=/";
// Modern async alternative (Chromium-based browsers)
const lang = await cookieStore.get("lang");HttpOnly cookies never appear in document.cookie; only the server can set or read them. Encode values with encodeURIComponent if they may contain special characters.
Q6. Why are cookies used for sessions instead of localStorage?#
Answer: cookies are sent automatically with requests, including the initial HTML request, which makes server-side rendering of authenticated pages possible. With HttpOnly, the session ID can't be read by injected scripts. The trade-off is CSRF exposure, handled by SameSite and CSRF tokens. localStorage tokens must be attached manually by JavaScript and can be stolen by any XSS. More in frontend security interview questions.
Q7. What are first-party and third-party cookies? What is changing?#
Answer: a first-party cookie belongs to the site in the address bar. A third-party cookie belongs to another domain loaded on the page (an ad network or embedded widget) and has been used for cross-site tracking. Safari and Firefox block third-party cookies by default, and browsers are adding privacy features like CHIPS (partitioned cookies with the Partitioned attribute, keyed to the top-level site) and storage partitioning. Embedded widgets that relied on third-party cookies need alternatives such as partitioned cookies or the Storage Access API.
Larger and advanced storage#
Q8. What is IndexedDB, and when should you use it?#
// Using the small "idb" wrapper library for a promise-based API
import { openDB } from "idb";
const db = await openDB("notes-app", 1, {
upgrade(db) {
const store = db.createObjectStore("notes", { keyPath: "id" });
store.createIndex("byUpdated", "updatedAt");
},
});
await db.put("notes", { id: "n1", title: "Groceries", body: "Milk, eggs", updatedAt: Date.now() });
const note = await db.get("notes", "n1");
const recent = await db.getAllFromIndex("notes", "byUpdated");Answer: IndexedDB is a transactional, asynchronous, NoSQL database in the browser. It stores structured data (objects, arrays, Blobs and Files, not just strings), supports indexes and transactions, works in Web Workers and service workers, and can hold far more data than localStorage. Use it for offline-first apps, caching API data, drafts and large datasets. The raw API is event-based and verbose, so wrappers like idb or Dexie are common.
Q9. How do you sync data across tabs?#
// Fires in OTHER tabs of the same origin when localStorage changes
window.addEventListener("storage", (event) => {
if (event.key === "auth" && event.newValue === null) {
location.assign("/login"); // user logged out in another tab
}
});
// BroadcastChannel: send any message between same-origin tabs
const channel = new BroadcastChannel("cart");
channel.postMessage({ type: "item-added", id: 42 });
channel.onmessage = (e) => refreshCart(e.data);Answer: the storage event fires in every other same-origin tab when localStorage changes (not in the tab that made the change, and not for sessionStorage across tabs). BroadcastChannel is a cleaner way to send messages between tabs, such as logout or cart updates.
Q10. What is the Cache API, and how is it different from the HTTP cache?#
Answer: the Cache API (caches.open()) stores Request/Response pairs that your code controls explicitly, usually from a service worker to make apps work offline. The HTTP cache is managed automatically by the browser according to response headers like Cache-Control. Cache API entries stay until your code deletes them (or the browser evicts the origin's storage). Details are in HTTP caching and service worker interview questions.
Limits, eviction and choosing#
Q11. What are storage limits, and when does the browser delete data?#
const { usage, quota } = await navigator.storage.estimate();
console.log(`Using ${(usage / 1e6).toFixed(1)}MB of ${(quota / 1e6).toFixed(0)}MB`);
// Ask the browser not to evict this origin's data under storage pressure
const persisted = await navigator.storage.persist();localStorageandsessionStorageare capped around 5MB per origin; exceeding it throws aQuotaExceededError.- IndexedDB and the Cache API share a much larger quota that depends on free disk space.
- Storage is "best effort" by default: under disk pressure the browser may evict an origin's data, usually the least recently used.
navigator.storage.persist()requests persistent storage. - Safari may clear script-written storage for sites the user hasn't interacted with for a few days (Intelligent Tracking Prevention), and private browsing modes clear everything when closed.
Never treat browser storage as the only copy of important data; sync to a server.
Q12. What should you never store in browser storage, and how do you choose?#
Never store: passwords, full card numbers, private API keys or other secrets, and long-lived auth tokens in localStorage. Anything in client storage can be read by the user and by any script running on the page, and it stays on shared devices.
| Need | Best choice |
|---|---|
| Server session / authentication | HttpOnly; Secure; SameSite cookie |
| Theme, language, dismissed banners | localStorage (or a cookie if the server renders with it) |
| Multi-step form progress in one tab | sessionStorage |
| Offline data, large or structured records, files | IndexedDB |
| Offline copies of pages and assets | Cache API in a service worker |
| State that must be shareable as a link | URL query parameters |
Quick revision#
| Storage | Size | Lifetime | Sent to server |
|---|---|---|---|
| Cookie | ~4KB | Expiry or session | Yes |
localStorage | ~5MB | Until cleared | No |
sessionStorage | ~5MB | Tab session | No |
| IndexedDB | Large (disk-based) | Until cleared or evicted | No |
Related: promises and async/await interview questions and frontend system design interview questions.
Key takeaways#
- Cookies are small and sent with requests; Web Storage is larger, client-only and string-based.
localStoragepersists and is shared across tabs;sessionStorageis per tab and cleared on close.- Secure session cookies with
HttpOnly,SecureandSameSite, and keep secrets out of client storage. - Use IndexedDB for large or structured data and the Cache API for offline responses.
- Expect quotas, eviction and privacy restrictions, and sync important data to a server.