Two simple stores
The Web Storage API offers two synchronous key value stores scoped to an origin.
- localStorage persists until explicitly cleared, surviving browser restarts
- sessionStorage lasts only for the lifetime of the tab or page session
- Both store strings only, so objects must be serialised with JSON stringify
The basic operations
Both share the same interface: setItem, getItem, removeItem, and clear. Keys and values are always strings, and getItem returns null for a missing key.
Limits and gotchas
- Capacity is roughly five to ten megabytes per origin
- Access is synchronous, so large reads can block the main thread
- It is not secure storage, so never store tokens or secrets there
- Writing fires a storage event in other tabs of the same origin
Choosing between them
Use localStorage for preferences like theme that should persist. Use sessionStorage for transient per tab state like a multi step form in progress.
Key idea
Web Storage holds string key value pairs per origin; localStorage persists indefinitely while sessionStorage clears when the tab closes.