sessionStorage
sessionStorage is a string key/value store scoped to an origin and a tab (a browsing session). Closing the tab clears it. A new tab does not see the old tab's data.
Detailed Explanation
The API matches localStorage: setItem, getItem, removeItem, clear, key(i), length. Values are strings. Quota is similar (megabytes, origin-dependent). Access is synchronous.
The difference is lifetime and isolation. localStorage is shared by every tab of https://app.example. sessionStorage is copied when you duplicate a tab (the clone gets a copy at fork time) but a user-opened new tab starts empty. Refresh keeps it. A new window to the same URL is a new session.
Use it for wizard state, a one-tab draft, or a "this tab is the OAuth popup's opener context" flag. Do not use it for data the user expects to see after they close the phone browser. Do not use it for secrets; XSS in this tab still reads it.
The storage event does not fire for sessionStorage in other tabs the way it does for localStorage (there is no other tab sharing that area, except the duplicate-tab case which is already a copy). Do not rely on cross-tab sync with sessionStorage.
What it costs you: surprise when a user "opens in new tab" and loses the wizard. Document that the flow is tab-local, or persist to the server / localStorage.
Reach for sessionStorage when the data should die with the tab. Reach for localStorage when it should follow the user across tabs. Reach for a cookie when the server must see it.
OAuth popups and window.open flows often stash a state parameter in sessionStorage on the opener. The popup cannot read another origin’s store. Same-origin opener and popup do not share sessionStorage; they are different sessions. Pass state in the URL or window.name / postMessage instead of assuming the child sees the parent’s session store.
Quota errors here are rarer than localStorage because the data set is smaller, but a debug dump of a 2 MB draft on every keystroke will still throw.
Code Examples
sessionStorage.setItem("wizardStep", "2");
console.log(sessionStorage.getItem("wizardStep")); // => 2
sessionStorage.removeItem("wizardStep");
console.log(sessionStorage.getItem("wizardStep")); // => nullfunction pushDraft(text) {
sessionStorage.setItem("draft", text);
}
function popDraft() {
const text = sessionStorage.getItem("draft") ?? "";
sessionStorage.removeItem("draft");
return text;
}
pushDraft("hello");
console.log(popDraft()); // => helloCommon Gotchas
A new tab is a new store
"open in new tab" will not see this tab's `sessionStorage`.
Duplicating a tab copies the store at that moment
later writes diverge.
Values are strings
`setItem("n", 1)` stores `"1"`. JSON-encode objects.
Still XSS-visible
not a safe place for tokens.