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 Velloreth
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
| localStorage | IndexedDB | |
|---|---|---|
| Sync | yes | no |
| Type | a string | an object |
| Size | a few MB | large |
| Index | no | yes |
| Transaction | no | yes |
| Blocks the thread | yes | no |
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
| Use | Store |
|---|---|
| A small setting | localStorage |
| A session value | sessionStorage |
| A large dataset | IndexedDB |
| A file blob | IndexedDB |
| A cache of an API | the Cache API |
| A cookie | a 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.
Related reading
For the related topics, see localstorage-vs-sessionstorage and service-workers-explained. For the broader context, progressive-web-apps-guide and caching-strategies-guide.