TExcelTAD
Home › JavaScript › Web Storage

Web Storage

The Web Storage API lets a page save small amounts of data in the browser as key–value pairs, so it's still there after a reload — preferences like dark mode, a draft message, the contents of a shopping cart. There are two stores with the same API:

localStorage sessionStorage
Lifetime until cleared by the site or the user until the tab is closed
Shared between all tabs of the same origin only the current tab
Typical use preferences, saved state wizard steps, per-tab state
Capacity about 5 MB per origin about 5 MB per origin

Data is stored per origin (protocol + host + port): https://example.com can't read the storage of https://other.com.

The API

js
localStorage.setItem("theme", "dark");       // save (value is converted to a string)
localStorage.getItem("theme");               // "dark"  (null if missing)
localStorage.removeItem("theme");            // delete one key
localStorage.clear();                        // delete everything for this origin
localStorage.length;                         // number of keys
localStorage.key(0);                         // name of the first key

Keys and values are always strings. To store numbers, arrays or objects, convert them with JSON.stringify when saving and JSON.parse when loading:

js
const cart = [{ id: 7, qty: 2 }];
localStorage.setItem("cart", JSON.stringify(cart));
const saved = JSON.parse(localStorage.getItem("cart") ?? "[]");

Storage in sandboxed frames

The playgrounds on this site run in sandboxed iframes without a real origin (for your safety, they can't touch this site's data). In such a frame, merely accessing localStorage throws a SecurityError. Real pages can also hit storage errors — private browsing modes, disabled cookies/site data, or a full quota.

So robust code always wraps storage access in try…catch and falls back gracefully. The example below detects whether storage works and otherwise uses an in-memory replacement with the same methods — the app keeps working, it just won't remember anything after a reload:

html · try it yourself
<p id="status"></p>
<script>
  function getStorage() {
    try {
      const store = window.localStorage;           // may throw in sandboxed frames
      const probe = "__storage_test__";
      store.setItem(probe, probe);                 // may throw if full or disabled
      store.removeItem(probe);
      return { store, persistent: true };
    } catch (err) {
      console.log(`localStorage unavailable (${err.name}) — using memory instead`);
      const data = new Map();
      const memory = {
        getItem: (k) => (data.has(k) ? data.get(k) : null),
        setItem: (k, v) => data.set(k, String(v)),
        removeItem: (k) => data.delete(k),
        clear: () => data.clear(),
        get length() { return data.size; },
      };
      return { store: memory, persistent: false };
    }
  }

  const { store, persistent } = getStorage();
  document.getElementById("status").textContent = persistent
    ? "✔ Real localStorage is available — data survives reloads."
    : "ⓘ Running with in-memory storage — data is lost on reload.";

  store.setItem("greeting", "hello");
  console.log("read back:", store.getItem("greeting"));
  console.log("missing key:", store.getItem("nope"));
</script>

On a normal page (for example your own project served by Vite), the first branch succeeds and the data persists.

A persistent preference

Here's a theme switcher that remembers the choice when storage is available. It uses the same safe wrapper, written as two tiny helper functions:

html · try it yourself
<style>
  body { font-family: system-ui, sans-serif; transition: background .2s, color .2s; padding: 8px; }
  body.dark { background: #1e1e1e; color: #eee; }
</style>
<label><input type="checkbox" id="dark"> Dark mode</label>
<p>Reload the page: the setting is remembered if storage is available.</p>
<script>
  function load(key, fallback) {
    try {
      const raw = localStorage.getItem(key);
      return raw === null ? fallback : JSON.parse(raw);
    } catch {
      return fallback;                       // blocked storage or corrupt JSON
    }
  }
  function save(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch {
      return false;                          // blocked or quota exceeded
    }
  }

  const box = document.getElementById("dark");
  const prefs = load("prefs", { dark: false });
  box.checked = prefs.dark;
  document.body.classList.toggle("dark", prefs.dark);

  box.addEventListener("change", () => {
    prefs.dark = box.checked;
    document.body.classList.toggle("dark", prefs.dark);
    console.log(save("prefs", prefs) ? "saved" : "could not save (storage blocked)");
  });
</script>

Syncing between tabs

When one tab changes localStorage, every other tab of the same origin receives a storage event — useful for keeping a logged-out state or a cart in sync:

js
window.addEventListener("storage", (event) => {
  console.log(`${event.key} changed from ${event.oldValue} to ${event.newValue}`);
});

What not to store

  • Secrets such as passwords or long-lived auth tokens: any script on the page (including a malicious injected one) can read storage. Prefer HttpOnly cookies for session tokens.
  • Large data or many records: use IndexedDB, which is asynchronous and can hold far more.
  • Data you can't afford to lose: users and browsers can clear storage at any time.

Tip: Storage access is synchronous and blocks the main thread. Read once at startup into a variable, and write only when something actually changes.

Test yourself

What type are values stored in localStorage?

  1. Any JavaScript value
  2. Strings
  3. Numbers and strings
  4. JSON objects

What is the difference between localStorage and sessionStorage?

  1. sessionStorage is bigger
  2. localStorage persists until cleared; sessionStorage lasts until the tab closes
  3. Only localStorage can store numbers
  4. sessionStorage is shared by all tabs

Why wrap localStorage access in try…catch?

  1. It is asynchronous
  2. Access can throw in sandboxed frames, private modes or when the quota is full
  3. getItem always throws for missing keys
  4. It's required by the JSON format