Web Storage: LocalStorage, SessionStorage, and the Limits of Client-Side State

localstorage vs sessionstorage explained: scope, lifetime, quotas, the storage event, Safari's 7-day cap, security risks, and when to use IndexedDB.

Executive Summary: localStorage and sessionStorage are small, synchronous, string-only key-value stores scoped to an origin. localStorage persists until cleared and is shared by every tab; sessionStorage lives only as long as one tab. They are ideal for small preferences and UI state, and the wrong place for authentication tokens, personal data, large datasets or anything you cannot afford to lose, because any script on the page can read them and browsers can delete them without asking.
Table of stored keys and values representing localStorage and sessionStorage

A web app stores the user’s access token in localStorage because it survives page reloads. Months later, a compromised analytics script reads it and sends it to another server. Elsewhere, an offline-capable notes app keeps drafts in localStorage, and Safari users report that their notes vanished after a week away. Both teams used Web Storage exactly as countless tutorials show. Both ran into limits the tutorials never mention.

Web Storage is a browser API with two objects. localStorage stores string key-value pairs per origin, persisting across tabs, windows and browser restarts. sessionStorage uses the same API but its data belongs to one tab and is cleared when that tab closes. An origin is the combination of scheme, host and port, so https://app.example.com and https://www.example.com have separate storage.

How does the Web Storage API work?

localStorage.setItem("theme", "dark");
localStorage.getItem("theme");        // "dark"
localStorage.getItem("missing");      // null
localStorage.removeItem("theme");
localStorage.clear();                 // removes everything for this origin
localStorage.length;                  // number of keys
localStorage.key(0);                  // name of the first key

// Values are always strings
localStorage.setItem("count", 3);
typeof localStorage.getItem("count"); // "string"

// Store structured data as JSON
localStorage.setItem("filters", JSON.stringify({ status: "open", sort: "due" }));
const filters = JSON.parse(localStorage.getItem("filters") ?? "{}");

Everything is a string. Storing an object without JSON.stringify gives you "[object Object]", and booleans come back as "true" and "false", both of which are truthy. Always serialize on write and parse with a fallback on read.

localStorage vs sessionStorage

localStorage sessionStorage
Lifetime Until cleared by code, the user or the browser Until the tab or window closes
Shared between tabs Yes, across all tabs of the origin No, each tab has its own
Survives reload Yes Yes
Survives browser restart Yes, unless cleared Usually not; some browsers restore it with “reopen tabs”
Duplicated tab Same data Starts with a copy of the original tab’s data, then diverges
Typical uses Theme, language, dismissed banners, recent searches Multi-step form progress, scroll position, one-tab wizard state

sessionStorage is underused. For state that belongs to one task in one tab, such as an unfinished checkout, it avoids a whole class of bugs where two tabs overwrite each other’s progress.

What are the limits of Web Storage?

Size

Browsers allow roughly 5 MB per origin for localStorage, and the same again for sessionStorage. The exact limit varies, and because strings are stored as UTF-16 in some engines, the number of characters you can store may be smaller than you expect. When you exceed it, setItem throws a QuotaExceededError. Code that does not catch it breaks in the middle of a user action.

It is synchronous

Every read and write blocks the main thread. For a few small keys this is negligible. Reading and parsing a 2 MB JSON blob on startup, or writing to storage on every keystroke, shows up as jank. Write on meaningful events, such as when a field loses focus, or debounce writes.

It can disappear

  • Users clear site data, and privacy extensions do it automatically.
  • Private and incognito windows keep storage only for the session.
  • Safari’s Intelligent Tracking Prevention deletes all script-writable storage, including localStorage and IndexedDB, for a site the user has not interacted with in seven days of browser use. Web apps added to the home screen are exempt.
  • Browsers may evict “best-effort” storage under disk pressure. navigator.storage.persist() asks for persistent storage, which browsers grant based on engagement or a permission prompt.

Treat Web Storage as a cache of convenience, never as the only copy of anything a user created.

Third-party contexts are partitioned

A widget in an iframe on another site used to share its localStorage across every site that embedded it, which made it a cross-site tracking tool. Safari and Firefox now partition storage for third-party contexts, giving the widget separate storage per top-level site, and Chrome began rolling out the same storage partitioning in mid-2023 with version 115. If your embedded chat widget or SSO iframe relied on shared storage, it no longer works the way it used to.

Is Web Storage secure?

Anything in localStorage is readable by every script running on your origin: your code, your npm dependencies, your tag manager, your A/B testing tool, and any script injected through a cross-site scripting bug. There is no equivalent of the HttpOnly flag that hides a cookie from JavaScript.

  • Do not store session tokens, refresh tokens or API keys in Web Storage. Use HttpOnly, Secure, SameSite cookies set by the server, which scripts cannot read.
  • Do not store personal or sensitive data such as addresses, health information or payment details. It sits unencrypted on the device and survives logout unless you remember to clear it.
  • Clear user-specific data on logout, especially on shared computers.
  • Validate what you read. Values can be edited by the user in DevTools or left over from an older version of your app, so never trust them for authorization.

How do you sync tabs with the storage event?

When one tab changes localStorage, every other tab of the same origin receives a storage event. The tab that made the change does not. This is a simple way to keep tabs consistent, for example logging out everywhere at once:

window.addEventListener("storage", (event) => {
  if (event.key === "auth:logout") {
    window.location.assign("/signed-out");
  }
  if (event.key === "theme") {
    document.documentElement.dataset.theme = event.newValue ?? "system";
  }
});

// In the tab where the user clicks Log out
localStorage.setItem("auth:logout", Date.now().toString());

For richer messaging between tabs, BroadcastChannel sends arbitrary messages without writing to storage at all.

A safer wrapper

Access can throw in several situations: quota exceeded, storage disabled by policy, or some privacy modes. A small wrapper keeps those failures from crashing the app and adds versioning so an old data shape does not break a new release:

const VERSION = 2;

export const store = {
  get(key, fallback = null) {
    try {
      const raw = localStorage.getItem(`app:v${VERSION}:${key}`);
      return raw === null ? fallback : JSON.parse(raw);
    } catch {
      return fallback;
    }
  },
  set(key, value) {
    try {
      localStorage.setItem(`app:v${VERSION}:${key}`, JSON.stringify(value));
      return true;
    } catch {
      return false;   // quota exceeded or storage unavailable
    }
  },
};

The key prefix also prevents collisions with other scripts on the same origin, which matters on sites where several apps or a CMS share one domain.

Which storage mechanism should you choose?

Need Use
Session or auth state the server must read Cookies, HttpOnly and Secure
Small preferences and UI state localStorage
State for one task in one tab sessionStorage
Large or structured data, offline records, binary files IndexedDB, often through a small library such as idb
Cached network responses for offline use Cache API with a service worker
Large files with fast random access Origin Private File System, now in all major browsers
Anything the user must never lose Your server

IndexedDB is asynchronous, stores structured objects and binary data without JSON conversion, supports indexes and transactions, and has quotas measured as a share of free disk space rather than a fixed 5 MB. navigator.storage.estimate() tells you how much your origin uses and how much is available.

Frequently Asked Questions

What is the difference between localStorage and sessionStorage?

Both store string key-value pairs per origin with the same API. localStorage persists until cleared and is shared across all tabs of the origin. sessionStorage belongs to a single tab and is cleared when that tab closes.

How much data can localStorage hold?

About 5 MB per origin in most browsers, with the exact limit varying by browser. Exceeding it throws a QuotaExceededError on setItem. For larger data, use IndexedDB, whose quota is based on available disk space.

Is it safe to store JWTs or tokens in localStorage?

It is risky. Any script on your origin, including third-party code or an injected script from an XSS bug, can read localStorage. Store session credentials in HttpOnly, Secure, SameSite cookies, which JavaScript cannot access.

Why did my localStorage data disappear?

Common causes are the user or an extension clearing site data, private browsing, storage eviction under low disk space, and Safari deleting script-writable storage for sites the user has not interacted with in seven days of use.

Convenient, not durable

Web Storage is the right tool for small, non-sensitive, recoverable state: the theme, the collapsed sidebar, the last-used filter. Use sessionStorage for single-tab tasks, IndexedDB for real data, cookies for authentication and your server for anything that matters. Wrap access in error handling, version your keys, and never let a script-readable store hold a secret. For the full reference, see the MDN Web Storage API guide and MDN on storage quotas and eviction. Related reading on this site: how hash tables work and web workers.

Originally posted on 11 September 2023 and post last modified on 11 September 2023

Front-End Development HTML5 JavaScript localStorage Web Storage

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *