JS sessionStorage API Guide: Complete Tutorial
Learn how to use sessionStorage to store temporary browser data that lasts only as long as the tab is open, with practical examples and real use cases.
sessionStorage is a browser API that stores key-value pairs scoped to a single browser tab. The data survives page reloads and navigation within the same site, but it disappears as soon as the user closes the tab or window. It is the Web Storage API's temporary counterpart to localStorage.
Here is the smallest useful sessionStorage example. You save a value, then read it back:
sessionStorage.setItem("cartStep", "2");
console.log(sessionStorage.getItem("cartStep"));The first line saves the string "2" under the key "cartStep". The second line reads it back and prints it.
2The code is identical to localStorage. The only difference is the lifetime. If you close the tab and reopen the same page, getItem returns null.
How sessionStorage differs from localStorage
sessionStorage and localStorage share the same API surface. The decision of which to use comes down to whether the data should survive after the user closes the tab.
| sessionStorage | localStorage | |
|---|---|---|
| Lifetime | Until tab closes | Forever, until manually deleted |
| Shared across tabs | No | Yes |
| Survives browser restart | No | Yes |
| Capacity | About 5 MB | About 5 MB |
| Data type | Strings only | Strings only |
sessionStorage is isolated per tab. If you open the same site in three tabs, each tab has its own separate sessionStorage. localStorage, by contrast, is shared across all tabs from the same origin.
When to use sessionStorage
sessionStorage is the right fit when data should be tied to a single browsing session. Common use cases include multi-step forms where you keep the current step without polluting persistent storage. One-time tokens that should only be valid for this tab session are another good fit.
Temporary UI state like expanded accordion sections that should reset on the next visit works well with sessionStorage. Form draft safety nets prevent data loss on refresh, and isolated per-tab settings avoid cross-tab interference when needed.
For data that needs to survive a tab close, use localStorage instead. For data the server needs to read automatically, use cookies instead of sessionStorage.
The sessionStorage API
The API mirrors localStorage exactly. Four methods handle everyday usage:
- setItem saves a value under a key
- getItem reads a stored value, returning null when the key is missing
- removeItem deletes a single key
- clear deletes all keys for this tab's session
Basic usage
sessionStorage.setItem("preferredView", "grid");
sessionStorage.setItem("resultsPerPage", "20");
console.log(sessionStorage.getItem("preferredView"));
console.log(sessionStorage.getItem("resultsPerPage"));
sessionStorage.removeItem("resultsPerPage");
console.log(sessionStorage.getItem("resultsPerPage"));This code saves two preferences, reads them back to confirm they are stored, then deletes one of them. Here is what each console.log line prints in order:
grid
20
nullThe final getItem returns null because the key was removed. The pattern is the same as localStorage.
Non-string values
Just like localStorage, sessionStorage only stores strings. Convert values manually when reading them back:
- Numbers: call
Number()on the stored string. - Booleans: compare the stored string against
"true". - Objects: use
JSON.stringify()before saving andJSON.parse()after reading, wrapped in a try/catch.
Persisting data before the tab closes
The pagehide event lets you save critical state before the user navigates away. This is useful for moving sessionStorage data into localStorage as a safety net:
window.addEventListener("pagehide", () => {
const draft = sessionStorage.getItem("formDraft");
if (draft) {
localStorage.setItem("formDraftBackup", draft);
}
});When the user returns, your page can check localStorage for a backup and restore it into sessionStorage.
A practical example: form wizard state
Here is a pattern for keeping multi-step form data without a backend. First, define two helper functions that save and load a step's data:
function saveStep(stepName, data) {
sessionStorage.setItem(`step_${stepName}`, JSON.stringify(data));
sessionStorage.setItem("currentStep", stepName);
}
function loadStep(stepName) {
const raw = sessionStorage.getItem(`step_${stepName}`);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
}The saveStep function serializes the step data as JSON and records which step is currently active. The loadStep function reads the stored JSON string, parses it back into an object, and returns null if anything goes wrong during the process.
With these two small helper functions defined, you can now save and restore step data anywhere in your multi-step wizard code:
saveStep("personal", { name: "Rune", email: "rune@example.com" });
const personal = loadStep("personal");
console.log(personal.name);Running the save and load calls in sequence prints the name that was stored in the personal step, confirming the helper functions read back exactly what they saved:
RuneEach step is saved under a prefixed key like step_personal or step_address. If the user refreshes, the wizard reads currentStep to know where they left off and loadStep to restore the data. When the tab closes, everything is gone.
Checking availability
Some browsers restrict sessionStorage in private browsing mode. Test availability before relying on it:
function sessionStorageAvailable() {
try {
const testKey = "__session_test__";
sessionStorage.setItem(testKey, testKey);
sessionStorage.removeItem(testKey);
return true;
} catch {
return false;
}
}Always guard setItem calls in production code so a quota error does not break your page.
Common mistakes
- Expecting sessionStorage to be shared across tabs. Each tab is isolated.
- Relying on sessionStorage for crash recovery. Browser restore behavior varies.
- Storing sensitive data without encryption. sessionStorage is not encrypted.
- Forgetting the string-only rule. Storing true and reading it back gives the string "true".
- Calling sessionStorage in Node.js code. It is a browser-only API.
Related articles
- JS localStorage API Guide: A Complete Tutorial -- persistent storage that survives tab close
- Storing Complex Objects in JS localStorage Guide -- safe JSON serialization for both storage APIs
- How to Manage Cookies in JS: Complete Tutorial -- working with browser cookies
Quick reference
| Operation | Code |
|---|---|
| Save a value | sessionStorage.setItem("key", "value") |
| Read a value | sessionStorage.getItem("key") |
| Delete one key | sessionStorage.removeItem("key") |
| Delete all keys | sessionStorage.clear() |
| Lifetime | Clears when tab or window closes |
| Tab isolation | Each tab has its own sessionStorage |
Rune AI
Key Insights
- sessionStorage works exactly like localStorage but clears when the tab closes.
- Each tab has its own isolated sessionStorage, so data is not shared across tabs.
- Use sessionStorage for form drafts, multi-step wizards, and temporary tokens.
- The same string-only limitation applies. Convert numbers, booleans, and objects explicitly.
- Combine sessionStorage with the pagehide event to persist critical data before a tab closes.
Frequently Asked Questions
When does sessionStorage data get deleted?
Is sessionStorage shared between tabs?
How much data can sessionStorage hold?
Does sessionStorage survive a browser crash?
Conclusion
sessionStorage gives you a clean sandbox for temporary data that should never outlive a tab. Use it for form drafts, wizard state, and one-time tokens where leaving data behind after closing the tab would be a privacy problem or a bug. The API is identical to localStorage, so switching between the two is just a name change.
More in this topic
Using Decorators for Logging in JS Architecture
Learn how JavaScript decorators wrap class methods to add logging without touching the original code, including setup with Babel and how execution order works.
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.