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.stringifybeforesetItemandJSON.parseaftergetItem, andJSON.parsecan throw on malformed stored data (see JSON.parse() and JSON.stringify()). getItemfor a key that was never set returnsnull, notundefinedand not an error.- Storage is per-origin (scheme + host + port) β data set on
https://example.comis not visible tohttps://other.com, or even tohttp://example.com(different scheme). - Storage can fail β private browsing modes, browser settings, or exceeding the storage quota can
make
setItemthrow. Code that must not crash on that failure should wrap it intry/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.