localStorage & sessionStorage
What is Web Storage?
Section titled “What is Web Storage?”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 What this module covers
Section titled “What this module covers”This module walks you through everything you need to use Web Storage with confidence:
| Lesson | What you will learn |
|---|---|
| This page | What Web Storage is and how the two stores differ at a high level |
local-vs-session | Lifetime, tab scope, and origin rules in depth |
the-api | The full setItem / getItem / removeItem / clear / key(i) / length API |
json-and-objects | Storing and retrieving objects with JSON.stringify / JSON.parse |
storage-event-and-limits | The cross-tab storage event, the ~5 MB quota, and the sync-blocking caveat |
Your first runnable example
Section titled “Your first runnable example”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.