Skip to content
Velloreth
Web Development 4 min read

IndexedDB Basics: Storing Data in the Browser

IndexedDB is a real database in the browser. Learn the object store, the index, the transaction, and the async API.

By

What it is

A transactional, asynchronous database in the browser.

It stores structured objects, not only strings.

It supports an index, a transaction and a large dataset.

It is used for:

  • An offline app
  • A cache of a large dataset
  • A file blob
  • A queue of unsent requests

The comparison

localStorageIndexedDB
Syncyesno
Typea stringan object
Sizea few MBlarge
Indexnoyes
Transactionnoyes
Blocks the threadyesno

localStorage blocks the main thread, so it is unsuitable for a large dataset.

The object store

The equivalent of a table.

const store = db.createObjectStore('posts', { keyPath: 'id' });

A key path is a property of the record.

A key generator auto-increments.

db.createObjectStore('logs', { autoIncrement: true });

A store is created in an upgrade, not at run time.

The index

A secondary lookup.

const store = db.createObjectStore('posts', { keyPath: 'id' });
store.createIndex('by_tag', 'tag');
store.createIndex('by_date', 'publishedAt');

A query by the index is efficient.

const index = store.index('by_tag');
const request = index.getAll('javascript');

A unique index enforces a constraint.

store.createIndex('by_slug', 'slug', { unique: true });

The transaction

Every operation must be inside a transaction.

const tx = db.transaction('posts', 'readwrite');
const store = tx.objectStore('posts');
store.put({ id: 1, title: 'Hello' });

The mode is readonly or readwrite.

A transaction commits when it is done.

A transaction that is not used in a tick may auto-commit, which is a common bug.

The API

It is event-based.

const request = store.get(1);
request.onsuccess = () => console.log(request.result);
request.onerror = () => console.error(request.error);

A wrapper turns it into promises.

import { openDB } from 'idb';

const db = await openDB('blog', 1, {
  upgrade(db) {
    const store = db.createObjectStore('posts', { keyPath: 'id' });
    store.createIndex('by_tag', 'tag');
  },
});

await db.put('posts', { id: 1, title: 'Hello' });
const post = await db.get('posts', 1);

idb is a small promise wrapper, and Dexie is a larger one with a query builder.

The upgrade

The version number triggers the upgrade.

const db = await openDB('blog', 2, {
  upgrade(db, oldVersion) {
    if (oldVersion < 1) {
      db.createObjectStore('posts', { keyPath: 'id' });
    }
    if (oldVersion < 2) {
      db.createObjectStore('comments', { keyPath: 'id' });
    }
  },
});

A store is created or deleted in the upgrade, not at run time.

The version must be incremented for the upgrade to run.

The storage limit

It depends on the browser and the free disk.

It is usually a large fraction of the free space.

The browser may evict the data under storage pressure.

A persisted origin is protected.

if (navigator.storage && navigator.storage.persist) {
  await navigator.storage.persist();
}

The quota is available.

const { usage, quota } = await navigator.storage.estimate();

The use cases

UseStore
A small settinglocalStorage
A session valuesessionStorage
A large datasetIndexedDB
A file blobIndexedDB
A cache of an APIthe Cache API
A cookiea cookie

The Cache API is for a network response, and IndexedDB is for the application data.

Common mistakes

A transaction that is not used in a tick. An auto-commit.

A store created at run time. It must be in an upgrade.

A version not incremented. The upgrade does not run.

A large object stored per record. A slow read.

No index. A full scan.

A synchronous assumption. The API is async.

No error handling. A silent failure.

No quota check. A write fails.

A private value stored unencrypted. It is readable.

No fallback. A private mode may block it.

A quotable summary

IndexedDB is a transactional, asynchronous database in the browser that stores structured objects, supports an index and a transaction, and can hold a large dataset. An object store is like a table, an index is a secondary lookup, and every operation must be inside a transaction. The raw API is event-based, so a promise wrapper such as idb or Dexie is what most code should use, and a persisted origin protects the data from eviction.

For the related topics, see localstorage-vs-sessionstorage and service-workers-explained. For the broader context, progressive-web-apps-guide and caching-strategies-guide.

Frequently asked questions

What is IndexedDB?
A transactional, asynchronous database built into the browser. It stores structured objects, supports an index, and can hold a large amount of data. It is used for an offline app, a cache of a large dataset, and a file blob. It is not a key-value store like localStorage.
What is the difference between IndexedDB and localStorage?
localStorage is synchronous, string-only, and limited to a few megabytes. IndexedDB is asynchronous, stores structured objects, supports an index and a transaction, and can hold much more. localStorage blocks the main thread, so it is unsuitable for a large dataset.
What is an object store?
The equivalent of a table. It holds records keyed by a key path or a key generator. A record is a JavaScript object, and it can be indexed by a property. A store is created in an upgrade, not at run time.
What is a transaction?
A unit of work that groups one or more operations, with a mode of readonly or readwrite. Every operation must be inside a transaction, and a transaction commits when it is done. A transaction that is not used in a tick may auto-commit, which is a common bug.
Why is the IndexedDB API so awkward?
Because it is event-based and predates promises. A request fires a success or an error event, and the transaction has a lifecycle. A wrapper such as idb or Dexie turns it into promises, which is what most code should use.
How much data can IndexedDB hold?
It depends on the browser and the available disk, and it is usually a large fraction of the free space, often hundreds of megabytes or more. The browser may evict the data under storage pressure unless the origin is persisted with navigator.storage.persist().