Question

sessionStorage vs localStorage in JavaScript: Benefits and Use Cases

htmljavascriptlocal-storagesession-storage

Question

Apart from being non-persistent and scoped to the current browser tab or window, does sessionStorage offer any advantages over localStorage, such as better performance or different data-access behavior?

Short Answer

By the end of this page, you will understand the practical differences between sessionStorage and localStorage, when tab-scoped storage is useful, and why performance is usually not the deciding factor.

Concept

Both sessionStorage and localStorage are part of the Web Storage API. They store key/value pairs in the browser for a specific origin (protocol, host, and port).

The important difference is lifetime and sharing scope:

  • localStorage is shared by same-origin tabs and windows and remains available after the browser is closed and reopened.
  • sessionStorage belongs to one same-origin top-level browsing context—usually one browser tab. It is removed when that tab or window's page session ends.

sessionStorage is beneficial when data should exist only during one visit in one tab. This avoids unwanted sharing with other tabs and reduces the need to clean up temporary values later.

There is no web-standard guarantee that sessionStorage is faster than localStorage. Both APIs are synchronous: calling methods such as getItem() and setItem() blocks JavaScript until the operation completes. For small, occasional values this is usually fine. For frequent or large client-side data operations, consider asynchronous storage such as IndexedDB.

Neither storage type is appropriate for secrets such as passwords, access tokens that must be protected from JavaScript, or highly sensitive personal data. JavaScript running on the same origin—including malicious code introduced through an XSS vulnerability—can read both.

Mental Model

Think of browser storage as lockers in a building:

  • localStorage is a shared locker for everyone using the same company address. It stays there after everyone goes home, and employees in other rooms can use it.
  • sessionStorage is a temporary locker assigned to one visitor in one room. It is useful for items needed during that visitor's current stay, without affecting visitors in other rooms.

The temporary locker is not automatically more secure against someone who gains access to the room. It is mainly better at keeping one visitor's temporary work separate from another's.

Take Quiz

Syntax and Examples

Both APIs have nearly identical methods:

storage.setItem("key", "value");
const value = storage.getItem("key");
storage.removeItem("key");
storage.clear();

Use sessionStorage for tab-specific temporary state:

// Save the current step in a multi-step form.
sessionStorage.setItem("checkoutStep", "shipping");

const step = sessionStorage.getItem("checkoutStep");
console.log(step); // "shipping"

// Remove it when the checkout is complete.
sessionStorage.removeItem("checkoutStep");

Use localStorage for a preference that should remain available later:

localStorage.setItem("theme", "dark");

const theme = localStorage.getItem("theme") ?? "light";
document.documentElement.dataset.theme = theme;

Web Storage stores strings only. Convert objects with JSON:

const draft = { title: "Weekly report", body: "Notes..." };

sessionStorage.setItem("draft", JSON.stringify(draft));

const savedDraft = JSON.parse(sessionStorage.getItem("draft") ?? "null");
console.log(savedDraft?.title); // "Weekly report"

Step by Step Execution

Consider a site open in two tabs, Tab A and Tab B:

// Run in Tab A.
sessionStorage.setItem("selectedPlan", "pro");
localStorage.setItem("preferredCurrency", "USD");
  1. sessionStorage.setItem() stores "pro" in Tab A's page session.

  2. localStorage.setItem() stores "USD" for the site's origin.

  3. In Tab A, both values can be read:

    console.log(sessionStorage.getItem("selectedPlan")); // "pro"
    console.log(localStorage.getItem("preferredCurrency")); // "USD"
    
  4. In Tab B, opened independently on the same site:

    console.log(sessionStorage.getItem("selectedPlan")); // null
    console.log(localStorage.getItem("preferredCurrency")); // "USD"
    
  5. Closing Tab A ends its page session, so its selectedPlan value is no longer part of that tab's active session. The preferredCurrency value remains in localStorage until code or the user clears it.

Browsers may restore tabs after a restart in some situations, so do not use session lifetime as a strict guarantee for security-sensitive cleanup.

Real World Use Cases

sessionStorage is a good fit for temporary, tab-specific information:

  • Multi-step forms: Remember the current step while the user moves between pages in a checkout or application flow.
  • Draft content for one tab: Preserve an unfinished support request or report while the user navigates within that tab.
  • Post-login navigation intent: Save the page a user intended to visit, then redirect there after login.
  • One-tab UI state: Keep an active filter, wizard state, or dismissed message isolated when users have several tabs open.
  • Temporary redirect data: Store short-lived state needed across a redirect, then remove it after use.

localStorage is usually better for values that should be reused across tabs and future visits, such as theme preference, language preference, or a recently viewed-items list.

Take Quiz

Real Codebase Usage

In production code, developers commonly wrap storage access so missing values, invalid JSON, and browser restrictions are handled consistently.

Guard against unavailable storage

Some browser privacy modes or embedded contexts can restrict storage. A small helper prevents one storage failure from breaking the page:

function saveSessionValue(key, value) {
  try {
    sessionStorage.setItem(key, JSON.stringify(value));
  } catch (error) {
    console.warn("Could not save session data", error);
  }
}

Validate values after reading

Storage can be cleared by users, old code may have saved a different format, and JSON may be invalid. Treat stored data as optional input:

function getCheckoutStep() {
  const step = sessionStorage.getItem("checkoutStep");
  const allowedSteps = ["cart", "shipping", "payment"];

  return allowedSteps.includes(step) ? step : "cart";
}

Remove temporary state deliberately

Clear a session value once its purpose is complete:

function finishCheckout() {
  sessionStorage.removeItem("checkoutStep");
  window.location.assign("/order-confirmation");
}

Use namespaced keys

Prefixes reduce collisions in larger applications:

sessionStorage.setItem("checkout:step", "payment");
sessionStorage.setItem("checkout:draft", JSON.stringify({ email: "a@example.com" }));

Avoid reading or writing storage repeatedly in tight loops or on every animation frame because the API is synchronous.

Common Mistakes

Assuming sessionStorage is always faster

There is no standard performance promise that makes sessionStorage faster than localStorage. Pick based on scope and lifetime, then measure if performance matters.

Storing objects without JSON conversion

This stores "[object Object]", not a usable object:

// Incorrect
sessionStorage.setItem("profile", { name: "Ava" });

Convert the object first:

sessionStorage.setItem("profile", JSON.stringify({ name: "Ava" }));

Forgetting that getItem() can return null

const raw = sessionStorage.getItem("draft");
const draft = JSON.parse(raw); // Error when raw is null

Use a fallback or check first:

const raw = sessionStorage.getItem("draft");
const draft = raw ? JSON.parse(raw) : null;

Treating browser storage as secure secret storage

Do not store passwords, private keys, or other secrets that must not be exposed to JavaScript. An XSS attack can access both localStorage and sessionStorage.

Expecting sessionStorage to synchronize between tabs

Each tab has its own session storage area. If tabs must share state, use localStorage, BroadcastChannel, a server, or another deliberate communication mechanism.

Assuming values are automatically deleted when a workflow finishes

A session can continue as users navigate. Remove temporary values when they are no longer useful.

Comparisons

FeaturesessionStoragelocalStorage
ScopeOne origin and one top-level browsing context, usually one tabOne origin, shared across same-origin tabs and windows
Typical lifetimeCurrent tab/window page sessionUntil explicitly cleared by code or the user
Survives closing a tabNoYes
Shared with another independently opened tabNoYes
API methodsgetItem, setItem, removeItem, cleargetItem, setItem, removeItem, clear
Stored value typeStringsStrings
Standard speed advantageNone guaranteedNone guaranteed
Suitable for secretsNoNo

Web Storage vs cookies

FeatureWeb StorageCookies
Automatically sent with HTTP requestsNoUsually yes, depending on cookie settings
Accessible to JavaScriptYesYes, unless the cookie is HttpOnly
Common useClient-side UI state and preferencesServer-managed sessions and request-related state

A server authentication cookie marked HttpOnly, Secure, and with an appropriate SameSite setting can protect its value from JavaScript. Neither localStorage nor sessionStorage provides that protection.

Take Quiz

Cheat Sheet

// Write
sessionStorage.setItem("key", "value");
localStorage.setItem("key", "value");

// Read: returns a string or null
const value = sessionStorage.getItem("key");

// Delete one value
sessionStorage.removeItem("key");

// Delete every value for this storage area
sessionStorage.clear();

// Store an object
sessionStorage.setItem("user", JSON.stringify({ id: 42 }));
const user = JSON.parse(sessionStorage.getItem("user") ?? "null");
  • Use sessionStorage for temporary state isolated to one tab.
  • Use localStorage for persistent state shared across same-origin tabs.
  • Both are synchronous and string-only.
  • getItem() returns null when a key is absent.
  • Do not store sensitive secrets in either API.
  • Use try...catch when storage access might be unavailable or quota-limited.
  • Remove temporary values when the workflow completes.

FAQ

Is sessionStorage faster than localStorage?

Neither API has a guaranteed speed advantage. Both are synchronous browser APIs. Choose based on required lifetime and tab isolation; measure real workloads if needed.

Is sessionStorage shared between browser tabs?

No. An independently opened same-origin tab has its own sessionStorage. Same-origin tabs share localStorage instead.

Does sessionStorage survive page refreshes?

Yes. Refreshing or navigating within the same tab normally keeps the tab's page session storage available.

When is sessionStorage cleared?

It is associated with the tab or window's page session and is normally cleared when that browsing context is closed. Do not rely on this behavior as a security cleanup mechanism, since browser session restoration can affect user-visible behavior.

Can I store arrays and objects in sessionStorage?

Yes, but serialize them using JSON.stringify() and parse them with JSON.parse() when reading.

Can sessionStorage store an authentication token safely?

It is not a safe place for a token that must be protected from JavaScript, because XSS can read it. Choose an authentication design appropriate for your threat model, often involving secure server-managed cookies.

Does localStorage notify other tabs when it changes?

Other same-origin browsing contexts can receive a storage event when localStorage changes. sessionStorage is isolated to its own top-level browsing context, so it is not a cross-tab synchronization tool.

Take Quiz

Mini Project

Description

Build a small checkout-progress helper. It saves the user's current checkout step for the current tab, restores it after a refresh, and removes it when checkout is completed. This demonstrates why tab-specific temporary state is a practical use for sessionStorage.

Goal

Create a checkout flow that remembers a valid current step only within the active browser tab.

Requirements

Use sessionStorage to store the current checkout step.|Allow only cart, shipping, and payment as valid steps.|Restore the saved step when the page loads.|Reset to cart when the saved value is missing or invalid.|Remove the saved step when checkout is completed.

Take Quiz

Keep learning

Related questions

View more