localStorage vs IndexedDB: what is the difference?

IntermediateBrowser and web interview questionBy , updated 17 November 2026

Short answer

localStorage is a small, synchronous key-value store that holds only strings, good for a theme choice or a few settings. IndexedDB is an asynchronous, transactional database in the browser that stores structured data, including objects, dates, Blobs and files, with indexes and far larger limits, and it works in Web Workers and service workers. Use localStorage for tiny preferences and IndexedDB for real application data, caches and offline work.

Side-by-side comparison

localStorage IndexedDB
API Synchronous: getItem, setItem Asynchronous: requests, events and transactions
What it stores Strings only (you JSON.stringify the rest) Anything the structured clone algorithm supports: objects, arrays, Date, Map, Set, Blob, File, ArrayBuffer
Size Small, usually around 5 MB per origin Much larger, often a share of free disk space; varies by browser
Querying Look up by exact key Keys, key ranges, indexes, cursors
Transactions None Yes, all-or-nothing reads and writes
Workers and service workers Not available Available
Cross-tab change events storage event in other tabs None built in; use BroadcastChannel
Effort One line Verbose without a wrapper

Both are scoped to the origin, are readable by any script on the page (so neither is a safe place for secrets), and are cleared when the user clears site data. How localStorage compares with sessionStorage and cookies is covered in localStorage vs sessionStorage vs cookies.

Why synchronous matters

Every localStorage.getItem blocks the main thread until the value is read. For a few short strings that cost is negligible. For a megabyte of JSON read at startup and parsed with JSON.parse, it delays the first render and any input. IndexedDB never blocks: you start a request and get the result later, so large reads do not freeze the page.

Why structured clone matters

localStorage turns everything into strings. A Date comes back as a string, a Map becomes {}, undefined disappears, and binary data has to be Base64 encoded, which makes it about a third larger. IndexedDB stores real values through structured clone, so a Blob of a photo or an ArrayBuffer goes in and out unchanged. Functions, DOM nodes and class prototypes cannot be cloned; you get plain objects back.

Using IndexedDB directly

The raw API is built on events, which is why most people wrap it:

function openDb() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("notes-app", 1);
    request.onupgradeneeded = () => {
      // Runs when the database is new or the version number goes up
      const store = request.result.createObjectStore("notes", { keyPath: "id" });
      store.createIndex("byUpdated", "updatedAt");
    };
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

async function saveNote(note) {
  const db = await openDb();
  return new Promise((resolve, reject) => {
    const tx = db.transaction("notes", "readwrite");
    tx.objectStore("notes").put(note);
    tx.oncomplete = () => resolve();
    tx.onerror = () => reject(tx.error);
  });
}

Schema changes happen only in onupgradeneeded, triggered by a higher version number. If another tab still has the old version open, the upgrade is blocked until that tab closes its connection, so listen for versionchange and close the old connection.

The transaction auto-commit trap

A transaction commits automatically as soon as it has no pending requests and control returns to the event loop. If you await fetch() in the middle of a transaction, it commits while the network request is in flight, and the next put throws TransactionInactiveError. Fetch first, then open the transaction and write.

Wrappers

  • idb-keyval gives you a localStorage-like API on top of IndexedDB: await set("draft", draft) and const draft = await get("draft"). It is tiny and good when you only need key-value storage that is async and stores structured data.
  • idb wraps the full API in promises (await db.put("notes", note)) while keeping stores, indexes and transactions.
  • Dexie adds a query layer, schema versions and live queries for larger apps.

When to use each

localStorage: theme, language, a dismissed banner, the last tab opened, a feature flag override. Small, read on startup, not needed in a service worker.

IndexedDB: cached API responses for offline use, drafts and form data that must survive a crash, an outbox of requests to send when back online, images or files the user picked, large search indexes, anything a service worker must read. The service worker answer and the offline-first sync guide show how these fit together.

For cached HTTP responses themselves, the Cache API (caches.open) is usually the better fit, and for large files that you read and write in place, the Origin Private File System (navigator.storage.getDirectory()) exists.

Storage limits and eviction

By default, browser storage is "best effort": when the device runs low on space, the browser may delete an origin's data, usually starting with the least recently used sites. It removes everything for that origin together. Some browsers, Safari in particular, may also delete script-written storage for sites the user has not visited for some time. Plan for data loss: treat local data as a cache of the server, or sync it.

You can check usage and ask to keep data:

const { usage, quota } = await navigator.storage.estimate();
console.log(`Using ${Math.round(usage / 1e6)} MB of ${Math.round(quota / 1e6)} MB`);

if (navigator.storage.persist && !(await navigator.storage.persisted())) {
  const granted = await navigator.storage.persist();
  // granted is true if the browser will not evict this origin under pressure
}

Browsers decide persist() differently: some ask the user, others grant it based on how much the user engages with the site. Writes can also fail with QuotaExceededError in either store, so wrap them in try/catch.

Practise it

Common follow-up questions

Is IndexedDB faster than localStorage?

For a single tiny value, localStorage is quicker to call, because there is no transaction. For large or many values IndexedDB is better, mainly because it does not block the main thread, and because it skips the JSON.stringify and JSON.parse round trip.

Can a service worker use localStorage?

No. localStorage is synchronous, and synchronous storage is not available in workers or service workers. Use IndexedDB, or the Cache API for responses.

Should I store auth tokens in either?

Both are readable by any script that runs on the page, so a cross-site scripting bug exposes them. Where to store a JWT covers the trade-offs; an HttpOnly cookie is usually safer.

How do tabs stay in sync with IndexedDB?

There is no built-in change event. After a write, post a message on a BroadcastChannel, and have other tabs reload the affected data when they receive it.

Mistakes to avoid

  • Storing large JSON blobs in localStorage and parsing them on every page load

  • Awaiting a network request inside an IndexedDB transaction

  • Expecting Date, Map or class instances to survive localStorage

  • Treating browser storage as permanent; it can be evicted or cleared

  • Ignoring QuotaExceededError and failures in private browsing

  • Writing raw IndexedDB event code everywhere instead of using a small wrapper

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Fix an IndexedDB transaction that auto-commits during an await fetch()Medium35 min
  2. Build storage that survives private browsing and quota errorsMedium30 min
  3. Implement an offline-first data synchronization queue using IndexedDBHard75 min
  4. Design an offline-first PWA for field agents: offline forms, a photo upload queue, sync conflicts and storage limitsHard60 min
  5. Implement useLocalStorage() with serialization and cross-tab updatesMedium35 min