← Back to JavaScript, page 10

javascript-0192 · Medium mid

What is IndexedDB, how do object stores, indexes, and transactions work, and when do you choose it over localStorage?

IndexedDB is an asynchronous, transactional object database in the browser that stores structured-clonable values, blobs, and files, with indexes for queries and much larger quotas than localStorage. Work happens inside transactions on object stores, schema changes only happen in the upgrade handler, and every request is event or promise based. Choose it for large, structured, or offline data, and localStorage for tiny strings.

Full answer

localStorage is synchronous, stores strings only, and is limited to about 5 MB, so large values block the main thread. IndexedDB solves these limits.

Key concepts:

  • Database and version: indexedDB.open(name, version). When the version is higher than the stored one, onupgradeneeded runs. That is the only place to create or change object stores and indexes. Plan migrations by checking event.oldVersion.
  • Object store: like a table. It has a key path (keyPath: 'id') or generated keys (autoIncrement). Values can be objects, arrays, dates, blobs, and typed arrays, copied with the structured clone algorithm (no functions or DOM nodes).
  • Index: a secondary lookup on a property, such as email or createdAt. It lets you query by that property with ranges (IDBKeyRange.bound) and cursors, and can be unique.
  • Transaction: all reads and writes happen in a transaction with a mode (readonly or readwrite) and a list of stores. Transactions are atomic: if one request fails or you call abort(), none of the changes apply. A transaction closes automatically when no request is pending, so you cannot await unrelated work (like fetch) in the middle of it. By the time the work is done the transaction has finished, and using it throws an error (TransactionInactiveError for a new request on an inactive transaction, InvalidStateError once it is finished).
  • API style: the native API uses IDBRequest objects with onsuccess and onerror, so most projects wrap it in promises or use a small library such as idb or Dexie.
  • Cursors and getAll(query, count) read ranges. Use a key range and a limit instead of reading everything.
  • Durability and limits: data is per origin, can be evicted under storage pressure unless navigator.storage.persist() is granted, and may be unavailable in private modes in some browsers. Handle QuotaExceededError.
  • Multiple tabs: a version upgrade is blocked while another tab holds the old version open, so handle onversionchange by closing the connection.
  • It is available in workers and service workers, which localStorage is not.

Use it for offline queues, caches of API data, drafts, and files. Do not store secrets in it, since any script on the origin can read it.

javascript
require('fake-indexeddb/auto'); // Node.js only: a browser already has indexedDB

const request = (req) => new Promise((resolve, reject) => {
  req.onsuccess = () => resolve(req.result);
  req.onerror = () => reject(req.error);
});
const done = (tx) => new Promise((resolve, reject) => {
  tx.oncomplete = () => resolve();
  tx.onerror = () => reject(tx.error);
  tx.onabort = () => reject(tx.error ?? new Error('aborted'));
});

function open() {
  return new Promise((resolve, reject) => {
    const req = indexedDB.open('notes-db', 2);
    req.onupgradeneeded = (event) => {
      const db = req.result;
      console.log('upgrade from version', event.oldVersion, 'to', event.newVersion);
      if (event.oldVersion < 1) {
        const store = db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
        store.createIndex('byAuthor', 'author');
      }
      if (event.oldVersion < 2) req.transaction.objectStore('notes').createIndex('byDate', 'created');
    };
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
}

(async () => {
  const db = await open();
  console.log('stores:', [...db.objectStoreNames], '| indexes:', [...db.transaction('notes').objectStore('notes').indexNames]);

  const tx = db.transaction('notes', 'readwrite');
  const notes = tx.objectStore('notes');
  notes.add({ author: 'asha', text: 'first', created: 3 });
  notes.add({ author: 'ben', text: 'second', created: 1 });
  notes.add({ author: 'asha', text: 'third', created: 2, tags: ['js'], saved: new Date(0) });
  await done(tx);

  const read = db.transaction('notes').objectStore('notes');
  console.log('get by key:', await request(read.get(2)));
  console.log('by author index:', (await request(read.index('byAuthor').getAll('asha'))).map((n) => n.text));
  console.log('date range 1..2:', (await request(read.index('byDate').getAll(IDBKeyRange.bound(1, 2)))).map((n) => n.text));
  console.log('count:', await request(read.count()), '| structured clone keeps Date:', (await request(read.get(3))).saved instanceof Date);

  const failing = db.transaction('notes', 'readwrite');
  failing.objectStore('notes').add({ author: 'temp', text: 'will be rolled back', created: 9 });
  failing.abort();
  await done(failing).catch(() => {});
  console.log('count after abort:', await request(db.transaction('notes').objectStore('notes').count()));

  try {
    db.transaction('notes', 'readonly').objectStore('notes').add({ text: 'not allowed' });
  } catch (error) {
    console.log('write in readonly:', error.name);
  }

  const late = db.transaction('notes', 'readonly');
  await new Promise((resolve) => setTimeout(resolve, 5));
  try {
    late.objectStore('notes').get(1);
  } catch (error) {
    console.log('await between requests:', error.name);
  }

  try {
    db.transaction('notes', 'readwrite').objectStore('notes').add({ id: 1, author: 'dup', created: 0 }).onerror = (event) => {
      console.log('duplicate key:', event.target.error.name);
      event.preventDefault();
    };
    await new Promise((resolve) => setTimeout(resolve, 20));
  } catch (error) {
    console.log('sync error:', error.name);
  }
  db.close();
})();

Run with Node.js v24.22.1 as js-192.js; two runs gave identical output. Output: upgrade from version 0 to 2 stores: [ 'notes' ] | indexes: [ 'byAuthor', 'byDate' ] get by key: { author: 'ben', text: 'second', created: 1, id: 2 } by author index: [ 'first', 'third' ] date range 1..2: [ 'second', 'third' ] count: 3 | structured clone keeps Date: true count after abort: 3 write in readonly: ReadOnlyError await between requests: InvalidStateError duplicate key: ConstraintError

Key points

  • Asynchronous, transactional, structured-clone storage with indexes and large quotas.
  • Schema changes only in onupgradeneeded; plan versions and migrations.
  • Transactions are atomic and auto-close, so do not await unrelated async work inside them.
  • Use indexes, key ranges, and limits; wrap the API in promises or use idb or Dexie.
  • Handle quota, eviction, multi-tab version changes; do not store secrets.

Common mistakes

  • Awaiting fetch or other unrelated promises inside an open transaction.
  • Trying to create stores outside onupgradeneeded.
  • Reading a whole store to filter in JavaScript when an index and key range would do.
  • Storing secrets or assuming the data can never be evicted.

Follow-ups

  • How do you handle a version upgrade blocked by another tab?
  • When would you choose Dexie or idb?
  • How does the Cache API differ from IndexedDB?

Tips

  • Contrast with localStorage in size, sync versus async, and types.
  • Mention that transactions auto-close, since it is the usual bug.
  • Name a wrapper library and migrations by version.