🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Web Storage: localStorage, Cookies, and IndexedDB

Web FoundationsBrowser APIsđŸŸĸ Free Lesson

Web Storage: localStorage, Cookies, and IndexedDB

Every interesting web app needs to remember something between page loads: a theme preference, a shopping cart, a draft, a cache of reference data. The browser gives you four persistence mechanisms with very different costs, and most production bugs in this area come from picking the wrong one rather than from misusing the right one. Cookies ride on every request and top out at about four kilobytes. localStorage is a synchronous string key-value store with a five-to-ten megabyte budget. sessionStorage shares localStorage's interface but dies with the tab. IndexedDB is a real database — asynchronous, structured, capable of megabytes more — at the price of ceremony.

This lesson maps each mechanism to the jobs it actually fits, then shows the defensive patterns that keep client-side persistence from corrupting state or throwing in private browsing modes.

Four Layers, Four Contracts

StoreScopeSizeSent with requestsAccess model
CookiesPer path or domain~4 KB per cookieYes, every requestSynchronous document.cookie plus HTTP headers
localStoragePer origin~5–10 MBNoSynchronous string API
sessionStoragePer tab~5–10 MBNoSynchronous string API, cleared on tab close
IndexedDBPer originHundreds of MBNoAsynchronous object store with indexes

The scope column is the one to memorize. Cookies exist to authenticate and to carry server-readable state; everything else is for the page's own memory. A session token in localStorage works until a cross-site scripting bug turns it into a gift for an attacker, while an HttpOnly cookie survives the same bug. A cart in sessionStorage works until the user opens a second tab and watches their cart diverge.

A Defensive localStorage Wrapper

The localStorage API itself is three methods wide: setItem, getItem, removeItem, plus a length property and numeric index access. Everything that goes wrong happens around it — objects that must be serialized, quotas that throw, private windows that throw on write, and users who clear storage while your app is running:

javascript
const Store = {
  get(key, fallback = null) {
    try {
      const raw = window.localStorage.getItem(key);
      return raw === null ? fallback : JSON.parse(raw);
    } catch {
      return fallback;
    }
  },

  set(key, value) {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch (error) {
      console.warn('Storage write failed:', error);
      return false;
    }
  },

  remove(key) {
    try {
      window.localStorage.removeItem(key);
    } catch {
      /* storage unavailable */
    }
  }
};

Store.set('preferences', { theme: 'dark', density: 'compact' });
const prefs = Store.get('preferences', { theme: 'light', density: 'comfortable' });

Wrapping every access in try and catch is not paranoia: Safari's private mode historically threw on setItem, and any quota exhaustion throws QuotaExceededError mid-write. Returning a fallback instead of throwing keeps a broken storage layer from taking down the render. Note that getItem returns a string or null — never a parsed object — so serialization is mandatory for anything structured, and malformed JSON left by an older version of your app must not crash the new one.

sessionStorage and the Tab Lifecycle

sessionStorage mirrors the same API but scopes its contents to one tab, including tabs opened via window.open or a middle-click on a link. That property makes it the right home for multi-step wizard state that should reset when the journey ends, and the wrong home for anything the user expects to find after reopening the browser. Reloading a page restores its sessionStorage; duplicating the tab copies it in most browsers, which surprises people building per-tab filters.

A useful pattern: keep long-lived preferences in localStorage and per-tab working state in sessionStorage, and never mix the two under a single key. When the flow completes, remove the working copy explicitly rather than waiting for the tab to close — users keep tabs open for days.

Cookies When the Server Must See the Value

Reading and writing cookies from script goes through the document.cookie property, which is a serialized list rather than an object model. The attributes that matter in production are Secure, which restricts transmission to HTTPS; HttpOnly, which hides the cookie from script entirely and therefore from XSS; SameSite, which controls cross-site sending under Lax, Strict, or None; and Max-Age, a relative lifetime that is far easier to reason about than an absolute expires date:

javascript
document.cookie = 'theme=dark; max-age=31536000; path=/; SameSite=Lax; Secure';

function readCookie(name) {
  const match = document.cookie
    .split('; ')
    .find((row) => row.startsWith(name + '='));
  return match ? decodeURIComponent(match.split('=')[1]) : null;
}

const theme = readCookie('theme') || 'light';

The leading equals sign in the startsWith check matters when one cookie name prefixes another, and decodeURIComponent undoes the encoding the browser applies to values containing spaces or punctuation. Anything the server needs to act on — session tokens, consent flags, load-balancer affinity — belongs here, not in a store the server cannot read.

IndexedDB for Structured Data

Past a few megabytes of structured data, or any time you need indexes or atomic transactions, IndexedDB is the intended tool. The API is callback-based at the raw level; a small promise wrapper removes most of the ceremony:

javascript
function openDb() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('notes-app', 2);
    request.onupgradeneeded = () => {
      const db = request.result;
      if (!db.objectStoreNames.contains('notes')) {
        const store = db.createObjectStore('notes', { keyPath: 'id' });
        store.createIndex('by-updated', 'updatedAt');
      }
    };
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

async function saveNote(note) {
  const db = await openDb();
  return new Promise((resolve, reject) => {
    const tx = db.transaction('notes', 'readwrite');
    tx.objectStore('notes').put(note);
    tx.oncomplete = () => resolve();
    tx.onerror = () => reject(tx.error);
  });
}

async function recentNotes(limit = 20) {
  const db = await openDb();
  return new Promise((resolve, reject) => {
    const tx = db.transaction('notes', 'readonly');
    const index = tx.objectStore('notes').index('by-updated');
    const results = [];
    index.openCursor(null, 'prev').onsuccess = (event) => {
      const cursor = event.target.result;
      if (!cursor || results.length >= limit) return resolve(results);
      results.push(cursor.value);
      cursor.continue();
    };
    tx.onerror = () => reject(tx.error);
  });
}

The version number in open drives the upgrade callback: bump it whenever the schema changes and create stores there, never ad hoc after a successful open. Transactions auto-commit when their task queue empties, so all reads and writes for one logical operation belong in the same transaction — not spread across awaited microtasks after it has already committed.

Private Modes, Eviction, and What Survives

Modern browsers no longer usually hard-block storage writes, but they still evict. Intelligent tracking prevention and storage partitioning can clear or partition data based on user activity, and under sustained disk pressure the browser may drop IndexedDB and localStorage contents it judges expendable. Design for that reality: treat every client-side store as a cache, keep the server authoritative for anything the user would grieve losing, and version your stored payloads so an old format never poisons a fresh boot.

For data that genuinely must survive eviction — offline notes, downloaded media — the Storage Manager API lets you ask for a durable quota and check what you are using:

javascript
async function requestPersistence() {
  if (navigator.storage && navigator.storage.persist) {
    const granted = await navigator.storage.persist();
    console.log('Persistent storage granted:', granted);
  }
  if (navigator.storage && navigator.storage.estimate) {
    const { usage, quota } = await navigator.storage.estimate();
    console.log('Using', usage, 'of', quota, 'bytes');
  }
}

Browsers grant persistence based on engagement heuristics — bookmarked origins, high visit frequency — not on request alone, so treat a false result as a signal to keep the cache strategy aggressive rather than as a failure. Checking the estimate before writing large payloads also lets you prune stale entries instead of failing the write with a quota error after the fact.

One more cross-tab detail: the storage event fires in other tabs of the same origin when localStorage changes, which is the cheapest possible synchronization channel for theme or locale updates. Listen for it and re-read the key; do not post messages between tabs for state that already broadcasts itself.

🔒Client-side storage is readable by script

Anything in localStorage or sessionStorage is one injected script away from exfiltration. Never store credentials, session tokens that grant standing access, or personal data you have not already accepted shipping to the browser. Prefer HttpOnly cookies for authentication and keep localStorage for pure presentation state.

Common Mistakes

Storing session tokens in localStorage

Fix: Use HttpOnly, Secure, SameSite cookies so an XSS bug cannot read the token.

Calling JSON.parse on getItem without guarding against null or malformed data

Fix: Wrap access in try/catch and fall back to a default value.

Splitting one logical write across multiple IndexedDB transactions

Fix: Do all reads and writes for an operation inside a single transaction.

Putting per-tab wizard state in localStorage

Fix: Use sessionStorage for working state so a fresh tab starts clean.

Trusting that client storage persists forever

Fix: Treat it as a cache; keep the server authoritative and version your payloads.

Key Takeaways

  • Cookies are for server-readable state and authentication; localStorage and friends are the page's own memory.
  • localStorage and sessionStorage store strings only — serialize with JSON and guard every read.
  • Private modes and eviction policies make all client storage unreliable; wrap writes and keep server state authoritative.
  • Cookies need Secure, HttpOnly, and SameSite attributes to survive contact with real traffic and real attackers.
  • IndexedDB brings indexes and transactions; keep one logical operation inside one transaction.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement