Part III β The Speed Β· Lesson 6.3
Session Storage
In one lineSame API as localStorage, but the data dies when the tab does β and never leaves that tab.
Where you've seen itA multi-step application form open in two tabs for two different people, with neither overwriting the other.
Diagram
ISOLATION β per tab, not per origin
βββ Tab 1 βββββββββββββββ βββ Tab 2 βββββββββββββββ
β sessionStorage β β sessionStorage β
β draft = {name:"Asha"}β β draft = {name:"Ravi"}β
βββββββββββββββββββββββββ βββββββββββββββββββββββββ
β² independent copies, same origin, no collision
βββ Tab 1 βββββββββββββββ βββ Tab 2 βββββββββββββββ
β localStorage: draft βββΌβββΌββ same single value β
βββββββββββββββββββββββββ βββββββββββββββββββββββββ
β² one shared store β the two tabs fightLIFETIME β what survives what
action sessionStorage localStorage
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
reload (F5) β kept β kept
navigate away and back β kept β kept
restore tab after crash β often kept β kept
duplicate the tab β COPIED β shared
close the tab β gone β kept
open a new tab to the same site β empty β kept
browser restart β gone β keptHow it works
- Identical API to
localStorageβsetItem,getItem,removeItem,clear, strings only, ~5MB. - Scope is the tab plus the origin. A duplicated tab starts with a copy, then diverges.
- The
storageevent does not fire across tabs, because there's nothing shared to notify about. - Survives reloads and in-tab navigation, which makes it right for multi-page flows.
// step 2 of a wizard survives a refresh, but not a new tab
sessionStorage.setItem('claim:draft', JSON.stringify(form));
// on mount
const draft = JSON.parse(sessionStorage.getItem('claim:draft') ?? 'null');Trade-offs
Use sessionStorage | Use localStorage |
|---|---|
| Multi-step form drafts | Theme and locale |
| Scroll position for this visit | Dismissed banners |
| Per-tab UI state (open panel) | Feature-flag overrides |
| Anything that must not leak between tabs | Anything that should persist |
A note on tokens: sessionStorage is sometimes recommended for tokens "because it expires". It doesn't expire β it just ends with the tab, and it's equally readable by XSS. The reasoning in 3.5 still applies: prefer HttpOnly cookies.
Interview angle
"Session storage or local storage for a checkout flow?"
sessionStorage: the draft is meaningful only for this attempt, and two tabs must not overwrite each other.- It survives an accidental refresh, which is the actual failure users hit.
- Anything that must outlive the tab β a saved cart β belongs on the server, keyed to the user.
Recap
- Tab-scoped, origin-scoped, dies on close, copied on tab duplication.
- Right for wizards, drafts, and per-tab UI state.
- No cross-tab
storageevent, because nothing is shared.