localStorage

Persists small amounts of string data in the browser between page loads, scoped to the page's origin.

                localStorage.setItem(key, value) / localStorage.getItem(key) / localStorage.removeItem(key)
              

Purpose

localStorage persists key/value string data in the browser, scoped to the page’s origin, and available across page loads and browser restarts (until explicitly cleared).

Syntax

localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme'); // "dark", or null if never set
localStorage.removeItem('theme');
localStorage.clear(); // removes everything under this origin

Behavior notes

  • Every value is stored and returned as a string β€” storing structured data requires JSON.stringify before setItem and JSON.parse after getItem, and JSON.parse can throw on malformed stored data (see JSON.parse() and JSON.stringify()).
  • getItem for a key that was never set returns null, not undefined and not an error.
  • Storage is per-origin (scheme + host + port) β€” data set on https://example.com is not visible to https://other.com, or even to http://example.com (different scheme).
  • Storage can fail β€” private browsing modes, browser settings, or exceeding the storage quota can make setItem throw. Code that must not crash on that failure should wrap it in try/catch.
  • It’s synchronous and can block briefly on large amounts of data β€” not intended for large datasets; IndexedDB (covered in the Intermediate tier) is the browser storage API for that.

Common mistakes

  • Reading stored JSON without a try/catch, and crashing on corrupted or unexpectedly-shaped stored data.
  • Storing a versioned data shape (a settings object, for instance) without a version marker, making it hard to safely evolve the shape later without breaking data stored by an older version of the app.

Runtime notes

Part of the Web Storage standard β€” browser-only; Node has no built-in equivalent.

Taught in these lessons

Related reference

Updated 2026-09-03