Web Storage API Reference

localStorage and sessionStorage methods with quota limits and storage-event properties.

Reference for the Web Storage API — setItem, getItem, removeItem, clear, key and length — plus StorageEvent properties, per-origin quota limits and a localStorage vs sessionStorage comparison.

What is the difference between localStorage and sessionStorage?

localStorage persists until explicitly cleared and is shared across all tabs of the same origin. sessionStorage is scoped to a single tab and is wiped when that tab closes. They share the same Storage API but differ in lifetime and scope.

Simple key-value storage in the browser

The Web Storage API gives every origin two synchronous string key-value stores — localStorage and sessionStorage — sharing the same Storage interface but differing in lifetime and scope. This reference lists the methods and the length property, the StorageEvent fired on cross-tab changes, and the quota limits that trip up real apps.

How it works

Both areas expose the same handful of methods, and all values are strings:

localStorage.setItem("theme", JSON.stringify({ dark: true }));

const raw = localStorage.getItem("theme");
let theme = { dark: false };
try {
  const parsed = raw ? JSON.parse(raw) : null;
  if (parsed && typeof parsed.dark === "boolean") theme = parsed;
} catch {
  /* corrupt value — fall back to default */
}

window.addEventListener("storage", (e) => {
  if (e.key === "theme") applyTheme(e.newValue);
});

Writes are synchronous and can block the main thread, so keep payloads small. When you exceed the per-origin quota the call throws QuotaExceededError. The storage event lets other tabs of the same origin react to changes, but it never fires in the tab that wrote the value.

Tips and notes

  • Store strings only; serialise with JSON.stringify and validate the shape after JSON.parse.
  • Wrap writes in try/catch — private-browsing modes and full quotas both throw.
  • length and key(i) let you enumerate entries, but order is not guaranteed across browsers.
  • Use sessionStorage for per-tab, throwaway state and localStorage for data that should survive a reload.