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.

5 min read

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:

javascriptjavascript
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.

texttext
2

The 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.

sessionStoragelocalStorage
LifetimeUntil tab closesForever, until manually deleted
Shared across tabsNoYes
Survives browser restartNoYes
CapacityAbout 5 MBAbout 5 MB
Data typeStrings onlyStrings 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

javascriptjavascript
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:

texttext
grid
20
null

The 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 and JSON.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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

texttext
Rune

Each 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:

javascriptjavascript
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.

Quick reference

OperationCode
Save a valuesessionStorage.setItem("key", "value")
Read a valuesessionStorage.getItem("key")
Delete one keysessionStorage.removeItem("key")
Delete all keyssessionStorage.clear()
LifetimeClears when tab or window closes
Tab isolationEach tab has its own sessionStorage
Rune AI

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.
RunePowered by Rune AI

Frequently Asked Questions

When does sessionStorage data get deleted?

sessionStorage data is deleted when the user closes the tab or the browser window. Navigating to a different page on the same site does not clear it. Refreshing the page also preserves it.

Is sessionStorage shared between tabs?

No. Each tab gets its own isolated sessionStorage. Opening a link in a new tab that duplicates the session only works if the user opens the new tab from within the same page context. Most new tabs start with an empty sessionStorage.

How much data can sessionStorage hold?

Most browsers allow about 5 MB per origin, same as localStorage. The limit applies per origin across all active sessions, so many concurrent tabs storing large amounts can still trigger quota errors.

Does sessionStorage survive a browser crash?

Some browsers restore sessionStorage after a crash when they restore tabs. Do not rely on this behavior. Treat sessionStorage as volatile and always have a fallback.

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.