Tutorials JavaScript localStorage & sessionStorage
Ch 57 / 78
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above
Chapter 57 Intermediate 7 min read JavaScript

localStorage & sessionStorage

The Web Storage API gives every browser tab a simple key–value store built right into the browser — no database, no server, no setup. localStorage persists data across sessions (even after the tab closes), while sessionStorage lives only for the lifetime of a single tab. Together they are the go-to solution for saving user preferences, form drafts, auth tokens, and lightweight app state without any external dependency.

What you'll learn
How localStorage and sessionStorage differ
All five Storage methods — setItem, getItem, removeItem, clear, key
Storing objects with JSON.stringify / JSON.parse
Listening for storage changes with the storage event
Storage limits, security constraints, and gotchas
Real-world patterns — theme toggle, form autosave, cart

Two Stores, One API

Both storage types share an identical API — the only difference is how long data survives. Understanding when each one gets cleared is the single most important thing to know before you use them:

localStorage
Persistent Storage
Data is saved with no expiry. It survives browser restarts, tab closes, and even reboots. It is scoped to the origin (protocol + domain + port) and shared across all tabs of that origin.
Cleared by: explicit removeItem / clear(), user clearing browser data, or private browsing end
sessionStorage
Tab-Scoped Storage
Data lives only for the lifetime of the tab. Closing the tab wipes it. Each tab gets its own isolated sessionStorage — even two tabs on the same origin cannot read each other's session data.
Cleared by: closing the tab or window, navigating away (in some cases), or ending a private browsing session
Web Storage API
Same Interface, Different Scope
Both objects implement the exact same Storage interface — setItem, getItem, removeItem, clear, length, and key(n). Switching between them is a one-word change.
Limit: ~5 MB per origin (browser-dependent) · Strings only · Synchronous · Never sent to server

Storage API at a Glance

Both localStorage and sessionStorage are pre-built global objects — no constructor, no import needed. Every method works identically on both:

// ── Write ────────────────────────────────────────────
localStorage.setItem("theme", "dark");  // key, value (both strings)

// ── Read ─────────────────────────────────────────────
const theme = localStorage.getItem("theme");  // → "dark" | null if missing

// ── Delete one key ───────────────────────────────────
localStorage.removeItem("theme");

// ── Delete ALL keys in this origin ───────────────────
localStorage.clear();

// ── Count & enumerate ────────────────────────────────
localStorage.length;                            // number of stored keys
localStorage.key(0);                          // key name at index 0
localStorage = persistent across tabs sessionStorage = one tab only Values must be strings Returns null for missing keys

All Storage Methods in Detail

Both stores expose five methods and one property. Here is when and how to use each:

Write & Read
1
setItem(key, value) — stores a string value under the given key. Non-string values are auto-coerced to strings — always JSON.stringify objects.
2
getItem(key) — returns the stored string, or null if the key doesn't exist. Never returns undefined.
3
key(index) — returns the key name at the given numeric index. Useful for iterating all keys when combined with length.
Remove & Inspect
4
removeItem(key) — deletes a single key–value pair. Silently does nothing if the key does not exist — no error thrown.
5
clear() — removes every key–value pair from the store for the current origin. Use with caution — it affects all keys, not just yours.
6
length — a read-only property that gives the number of stored keys. Combine with key(i) to enumerate all entries in a loop.
JavaScript — All Five Methods
// 1. setItem — write
localStorage.setItem("username", "Alice");
localStorage.setItem("score", "42");                      // numbers become strings

// 2. getItem — read
const name = localStorage.getItem("username");          // "Alice"
const ghost = localStorage.getItem("nope");               // null

// 3. key(n) — enumerate
for (let i = 0; i < localStorage.length; i++) {
  const k = localStorage.key(i);
  console.log(k, localStorage.getItem(k));
}

// 4. removeItem — delete one key
localStorage.removeItem("score");                      // gone

// 5. clear — wipe everything for this origin
localStorage.clear();                                      // all keys removed

Storing Objects with JSON

Web Storage only stores strings. Trying to save an object directly stores the useless "[object Object]" string. Always use JSON.stringify to write and JSON.parse to read back objects:

// ❌ WRONG — object gets coerced to "[object Object]"
localStorage.setItem("user", { name: "Alice", age: 30 });
localStorage.getItem("user");   // → "[object Object]" 💥

// ✅ RIGHT — serialize with JSON.stringify, deserialize with JSON.parse
localStorage.setItem("user", JSON.stringify({ name: "Alice", age: 30 }));
const user = JSON.parse(localStorage.getItem("user"));
console.log(user.name);          // "Alice" ✅
JavaScript — Safe Read Helper with Fallback
// A reusable helper that handles JSON + missing key + parse errors
function readStorage(key, fallback = null) {
  try {
    const raw = localStorage.getItem(key);
    return raw !== null ? JSON.parse(raw) : fallback;
  } catch {
    return fallback;
  }
}

function writeStorage(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch (e) {
    console.warn("Storage full or disabled", e);
  }
}

// Usage
writeStorage("cart", [{ id: 1, qty: 2 }, { id: 4, qty: 1 }]);
const cart = readStorage("cart", []);            // [] if missing

localStorage vs sessionStorage — Full Comparison

Picking the right store is simple once you understand each dimension. Here's a complete side-by-side breakdown:

Feature localStorage sessionStorage
Persistence Until cleared — survives restarts Tab lifetime — gone on tab close
Scope All tabs of the same origin Single tab only — isolated per tab
Shared across tabs Yes No
Storage limit ~5 MB (browser-specific) ~5 MB (browser-specific)
Value type String only (use JSON for objects) String only (use JSON for objects)
Sent to server Never Never
Accessible from JS Yes — synchronous Yes — synchronous
Private browsing Cleared when private session ends Cleared when tab closes
Best for Theme, preferences, auth tokens Wizard steps, form drafts, one-time state
Approximate Storage Budgets (per origin)
localStorage
~5 MB
sessionStorage
~5 MB
Cookies
4 KB
IndexedDB
Disk %

The storage Event — Cross-Tab Sync

When localStorage changes in one tab, every other tab on the same origin receives a storage event — a built-in cross-tab communication channel. Note that the tab that made the change does not fire the event on itself:

JavaScript — storage Event
// Tab A — makes a change
localStorage.setItem("theme", "light");

// Tab B — listens for that change (fires in OTHER tabs only)
window.addEventListener("storage", (e) => {
  console.log(e.key);           // "theme"
  console.log(e.oldValue);     // "dark" (previous value)
  console.log(e.newValue);     // "light" (new value)
  console.log(e.storageArea);  // the localStorage object
  console.log(e.url);         // URL of the tab that changed it

  if (e.key === "theme") {
    document.documentElement.setAttribute("data-theme", e.newValue);
  }
});
sessionStorage never fires the storage event
The storage event is only emitted for localStorage changes. sessionStorage is isolated per tab, so there is no other tab to notify.

Key Method Reference

A bookmark-ready reference for every property and method on the Storage interface:

localStorage.setItem(key, value)
Stores value as a string under key. If the key already exists it is overwritten silently. Throws a QuotaExceededError (DOMException) if the storage quota is full — always wrap writes in try/catch for production code.
localStorage.getItem(key)
Returns the stored string value, or null if the key does not exist. Never returns undefined. Remember to JSON.parse if you stored an object.
localStorage.removeItem(key)
Removes the key–value pair for key. If the key does not exist the call is silently ignored — no error thrown. Safe to call speculatively.
localStorage.clear()
Removes every key for the current origin. This affects all stored data — yours and any third-party scripts sharing the origin. Use removeItem with a prefix pattern instead for safer cleanup.
localStorage.length
A read-only integer — the number of key–value pairs currently stored. Use it as the loop bound when iterating with key(i).
localStorage.key(index)
Returns the key name at position index, or null if out of range. Key order is browser-defined — do not rely on insertion order.
window "storage" event
Fires in other tabs when localStorage is modified. Event properties: key, oldValue, newValue, url, storageArea. Does not fire for sessionStorage changes.
sessionStorage (same API)
Identical interface to localStorage — just replace the global name. Data is isolated per tab and automatically cleared when the tab or window is closed.
Advertisement
📢 Ad space · 728 × 90 · Replace slot ID above

Real-World Use Cases

Here are the patterns you will encounter Web Storage used for in real projects:

Dark / Light Theme
Persist the user's chosen theme across browser sessions — read it immediately in a <head> script to avoid flash of wrong theme on page load.
localStorage
Shopping Cart
Store cart items as JSON so they survive page reloads and tab closes. Sync across tabs via the storage event to keep all open tabs consistent.
localStorage
Form Autosave
Auto-save draft form data on every keystroke using sessionStorage — draft disappears when the tab closes (no clutter), but survives accidental refreshes mid-entry.
sessionStorage
Multi-Step Wizard
Save progress between wizard steps in sessionStorage. If the user refreshes mid-flow they land back on the same step. Wiped on completion or tab close — no cleanup needed.
sessionStorage
Auth Token (short-lived)
Store JWTs or session IDs so users stay logged in across page reloads. For high-security apps prefer HttpOnly cookies — but for SPAs localStorage is common.
localStorage
User Preferences
Font size, language, layout density, notification settings — any preference the user sets once and expects to see next visit. No backend required for anonymous users.
localStorage
⚡
Free Resource
Download our JavaScript Cheat Sheet
Web Storage, Cookies, IndexedDB & all storage APIs — one page.
Get Sheet

Common Patterns

Three patterns you'll use in almost every real project that touches browser storage:

JavaScript — Pattern 1: Theme Persistence
// In <head> — runs before paint to avoid flash of wrong theme
(function () {
  const saved = localStorage.getItem("theme");
  const preferred = window.matchMedia("(prefers-color-scheme: dark)").matches
    ? "dark" : "light";
  document.documentElement.setAttribute("data-theme", saved || preferred);
})();

// Toggle button handler
function toggleTheme() {
  const next = document.documentElement.getAttribute("data-theme") === "dark"
    ? "light" : "dark";
  document.documentElement.setAttribute("data-theme", next);
  localStorage.setItem("theme", next);
}
JavaScript — Pattern 2: Form Autosave with sessionStorage
// Autosave every text field in a form — survives accidental refresh
const FORM_KEY = "contact-draft";

function saveDraft() {
  const form = document.getElementById("contactForm");
  const data = {};
  [...form.elements].forEach(el => {
    if (el.name) data[el.name] = el.value;
  });
  sessionStorage.setItem(FORM_KEY, JSON.stringify(data));
}

function restoreDraft() {
  const raw = sessionStorage.getItem(FORM_KEY);
  if (!raw) return;
  const data = JSON.parse(raw);
  const form = document.getElementById("contactForm");
  Object.entries(data).forEach(([k, v]) => {
    if (form.elements[k]) form.elements[k].value = v;
  });
}

// Debounced autosave + restore on load
document.getElementById("contactForm")?.addEventListener("input", () => {
  clearTimeout(window._draftTimer);
  window._draftTimer = setTimeout(saveDraft, 600);
});
document.addEventListener("DOMContentLoaded", restoreDraft);
JavaScript — Pattern 3: Namespaced Storage Wrapper
// Prefix all keys to avoid collisions with third-party scripts
function createStore(prefix, storage = localStorage) {
  const pre = k => `${prefix}:${k}`;
  return {
    get: (k, fb = null) => {
      try {
        const v = storage.getItem(pre(k));
        return v !== null ? JSON.parse(v) : fb;
      } catch { return fb; }
    },
    set: (k, v) => { try { storage.setItem(pre(k), JSON.stringify(v)); } catch {} },
    del: (k) => storage.removeItem(pre(k)),
    clear: () => {
      for (let i = storage.length - 1; i >= 0; i--) {
        const k = storage.key(i);
        if (k?.startsWith(prefix + ":")) storage.removeItem(k);
      }
    }
  };
}

const appStore = createStore("myapp");
appStore.set("theme", "dark");                // stores "myapp:theme"
appStore.get("theme", "light");             // "dark"
appStore.clear();                            // only clears "myapp:*" keys
Security Warning
Never store sensitive data (passwords, payment info, full SSNs) in localStorage or sessionStorage — any JavaScript running on the page (including third-party scripts and XSS injections) can read it. For auth tokens, prefer HttpOnly cookies which are inaccessible from JavaScript.
Quick Check
You store a user's cart in localStorage. The user closes the browser and reopens it the next day. What happens to the cart data?
Quick Check
You call localStorage.setItem("count", 5). What does localStorage.getItem("count") return, and what is its type?
Chapter Summary
  • The Web Storage API provides two synchronous key–value stores: localStorage (persists forever) and sessionStorage (lives for one tab session).
  • Both share the same five-method interface: setItem, getItem, removeItem, clear, and key(n), plus the length property.
  • Storage only holds strings. Always JSON.stringify objects before writing and JSON.parse after reading — and wrap in try/catch to handle parse errors gracefully.
  • localStorage is shared across all tabs of the same origin. sessionStorage is isolated per tab — two tabs cannot read each other's session data.
  • The storage event fires in other tabs when localStorage changes — a free cross-tab communication channel. It does not fire for sessionStorage.
  • Both stores have a limit of approximately 5 MB per origin. Exceeding it throws a QuotaExceededError — always wrap writes in try/catch in production.
  • Never store sensitive data in Web Storage — it is accessible to any JavaScript on the page. Use HttpOnly cookies for auth tokens in high-security applications.
  • Common patterns: theme persistence, shopping cart, form autosave (sessionStorage), multi-step wizard, and namespaced storage wrappers to avoid key collisions.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel