Guide · Browser storage

localStorage done right: a safe 30-line wrapper

localStorage is perfect for small things: a theme, a dismissed banner, a draft. It's also easy to misuse. Here's a tiny, dependency-free wrapper that adds expiration, versioning, quota handling and cross-tab sync, and the point where you should move to IndexedDB instead.

When localStorage is the right tool

  • Small, non-sensitive values: theme, language, layout preferences, dismissed notices.
  • Read once at startup and written occasionally.
  • Simple data that's easy to serialise as JSON.

If you're storing lists of records, files, or anything you'd want to query, skip ahead to IndexedDB and OPFS.

The pitfalls nobody handles

PitfallWhat happensFix
Quota exceededsetItem throwstry/catch every write
Storage blockedAccess can throw (privacy settings, some embedded contexts)Fall back to defaults
Strings onlyObjects become "[object Object]"JSON with a safe parse
No expiryStale data lives foreverStore a timestamp
Shape changesOld data breaks new codeStore a schema version
SynchronousLarge or frequent writes block the UIKeep values small, debounce writes

The wrapper

No dependencies, and it never throws: a broken or blocked storage just falls back to the default value.

JavaScript · store.js
const PREFIX = "app:";
const VERSION = 1; // bump when the shape of stored data changes

export const store = {
  get(key, fallback = null) {
    try {
      const raw = localStorage.getItem(PREFIX + key);
      if (raw === null) return fallback;
      const { v, exp, data } = JSON.parse(raw);
      if (v !== VERSION || (exp && Date.now() > exp)) {
        localStorage.removeItem(PREFIX + key); // outdated or expired
        return fallback;
      }
      return data;
    } catch {
      return fallback; // blocked storage or corrupt JSON
    }
  },

  set(key, data, { ttl = 0 } = {}) {
    try {
      const exp = ttl ? Date.now() + ttl : 0;
      localStorage.setItem(PREFIX + key, JSON.stringify({ v: VERSION, exp, data }));
      return true;
    } catch {
      return false; // QuotaExceededError or storage disabled
    }
  },

  remove(key) {
    try { localStorage.removeItem(PREFIX + key); } catch {}
  },
};
JavaScript · usage
import { store } from "./store.js";

store.set("theme", "dark");
store.set("promo-dismissed", true, { ttl: 7 * 24 * 60 * 60 * 1000 }); // 7 days

const theme = store.get("theme", "light");

Sync across tabs

When one tab writes, the browser fires a storage event in every other tab of the same site. That's all you need to keep open tabs consistent:

JavaScript · cross-tab sync
window.addEventListener("storage", (event) => {
  if (event.key !== "app:theme") return;
  const theme = store.get("theme", "light");
  document.documentElement.dataset.theme = theme;
});

Don't write on every change

Because localStorage is synchronous, saving a draft on every keystroke adds work to every keystroke. Debounce it:

JavaScript · debounced save
let timer;
editor.addEventListener("input", () => {
  clearTimeout(timer);
  timer = setTimeout(() => store.set("draft", editor.value), 400);
});

When to move to IndexedDB

  • You're storing more than a few hundred kilobytes, or a growing list of records.
  • You need to query or filter data, not just read one key.
  • You store files, images or binary data.
  • You want to do the work in a Web Worker, where localStorage isn't available.

That's where IndexedDB and OPFS come in. Compare them with a benchmark you can run in your browser.

FAQ

How much data can localStorage store?

Around 5 MB per origin in most browsers, stored as UTF-16 strings, so the practical limit for your data is often lower. When you go over, setItem throws a QuotaExceededError, which is why every write should be wrapped in try/catch.

Does localStorage expire?

No. Data stays until your code or the user clears it. To expire values, store a timestamp next to the data and check it on read, as the wrapper in this guide does. Use sessionStorage if data should only live as long as the tab.

Is localStorage slow or blocking?

It's synchronous, so every read and write runs on the main thread. For small values that's negligible. It becomes a problem with large values or frequent writes, such as saving on every keystroke or render. Debounce writes, and move large or structured data to IndexedDB.

Is it safe to store tokens in localStorage?

Avoid it for sensitive tokens. Any script running on your page, including injected ones in an XSS attack, can read localStorage. Prefer HttpOnly, Secure cookies for session tokens, and keep localStorage for non-sensitive preferences.

How do I sync localStorage between tabs?

Listen for the storage event on window. It fires in every other tab of the same origin when a value changes, not in the tab that made the change, so each tab can update its UI when another tab writes.