Skip to content

localStorage & sessionStorage

The Web Storage API gives every web origin two synchronous key/value stores built into the browser: localStorage and sessionStorage. Both share the same simple interface — you call setItem, getItem, removeItem, and clear — and both store all values as strings. There is no schema, no indexing, and no async overhead.

Web Storage is origin-scoped: a page at https://example.com cannot read the storage of https://other.com. This is enforced by the browser’s same-origin policy, not by any code you write.

The key difference between the two stores is lifetime and tab scope:

  • localStorage — data persists indefinitely (until explicitly deleted) and is shared across every tab and window open on the same origin.
  • sessionStorage — data lasts only for the life of a single browser tab (or window). Closing the tab clears it, and other tabs cannot see it.

localStorage vs sessionStorage at a glance

Section titled “localStorage vs sessionStorage at a glance”
flowchart LR
  subgraph LS[localStorage]
    direction LR
    LA[Tab A sets item] -->|writes| LStore[(origin-wide store)]
    LB[Tab B gets item] -->|reads same data| LStore
    LR[Browser restart] -->|data survives| LStore
  end
  subgraph SS[sessionStorage]
    direction LR
    SA[Tab A sets item] -->|writes| SStoreA[(Tab A store)]
    SB[Tab B] -->|own empty store| SStoreB[(Tab B store)]
    SC[Tab A closes] -->|store cleared| SStoreA
  end
localStorage persists and is shared across tabs; sessionStorage is per-tab and clears on close

This module walks you through everything you need to use Web Storage with confidence:

LessonWhat you will learn
This pageWhat Web Storage is and how the two stores differ at a high level
local-vs-sessionLifetime, tab scope, and origin rules in depth
the-apiThe full setItem / getItem / removeItem / clear / key(i) / length API
json-and-objectsStoring and retrieving objects with JSON.stringify / JSON.parse
storage-event-and-limitsThe cross-tab storage event, the ~5 MB quota, and the sync-blocking caveat

The snippet below writes a value to localStorage, reads it back, and then cleans up so it does not pollute your browser’s storage across page loads.

Browser Storage
Which Web Storage store survives a browser restart?
What data type does Web Storage use to store all values?
Can a page at https://app.example.com read the localStorage of https://api.example.com?