A schema-backed, asynchronous, high-capacity database built into every browser. IndexedDB stores structured data — objects, files, blobs — with indexed queries, transactional integrity, and storage measured in gigabytes. It is the foundation for offline-first apps, rich documents, caches, and any client-side data that outlives the session.
IndexedDBStorageBrowser API
1 · Requirements & Scoping
Before designing a storage layer, the first question is: why not localStorage? The answer is a table of constraints that IndexedDB was built to solve.
Functional requirements
Persist structured objects: Store JavaScript objects (not just string key-value pairs) with nested properties, arrays, dates, and binary blobs.
Indexed queries: Look up records by properties other than the primary key — email, role, creation date — without loading every record into memory.
Transactional integrity: Multiple read-write operations must succeed or fail atomically. A partial write corrupts the client state.
Async API: No blocking reads on the main thread. The API uses DOM events or promises (via wrappers) and returns control to the event loop between operations.
High capacity: Store hundreds of megabytes or gigabytes of data — documents, media files, cached API responses, user-generated content.
Schema versioning: Migrate the database schema across app versions. Old data must be transformed or preserved without breaking the running app.
Non-functional requirements
Performance: Reads complete within a single microtask. Writes batch within transactions to avoid disk thrashing. Index lookups are O(log n).
Storage quota: Must respect the browser storage quota (~60% of free disk, but varies by browser). The layer must detect and handle QuotaExceededError.
Cross-tab isolation: Two tabs writing to the same database must not corrupt each other's data. Transactions provide isolation.
Graceful degradation: If IndexedDB is unavailable (private browsing in some browsers, disk full), the app should fall back to in-memory storage or show a clear error.
Key Insight
IndexedDB is not a replacement for every storage need. If your data fits in 5 MB and never needs indexed lookups, localStorage is simpler and synchronous. If the data is exclusively binary files, consider OPFS (Origin Private File System). IndexedDB shines when you need structured data with multiple access paths, transactional writes, and capacity beyond the megabyte range.
2 · Architecture & Browser Landscape
IndexedDB does not live in isolation. It is one of several storage tiers available to a web page, each with different persistence, capacity, and access characteristics.
Figure 1 — Browser storage tier landscape. IndexedDB sits at the intersection of high capacity, permanent persistence, and native async access.
The architecture is layered. At the top sits the web app, which interacts with IndexedDB through the indexedDB global — a singleton namespace available in all modern browsers. Below that is the IndexedDB API layer, implemented natively in the browser engine (Blink, WebKit, Gecko). The API manages a connection pool, transaction scheduler, and the B-tree storage engine that persists data to the underlying SQLite database on disk.
Open/Connect pattern
Everything starts with indexedDB.open(). This request either opens an existing database or creates a new one. The version number determines schema upgrades: if the requested version is higher than the current version, onupgradeneeded fires, giving you the chance to create or modify object stores and indexes.
example.typescript
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open("AppDB", 3);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
// Create object store with auto-increment primary key
if (!db.objectStoreNames.contains("users")) {
const store = db.createObjectStore("users", {
keyPath: "id",
autoIncrement: true,
});
store.createIndex("email", "email", { unique: true });
store.createIndex("role", "role", { multiEntry: false });
store.createIndex("createdAt", "createdAt", { unique: false });
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
Schema versioning with migrations
The version number serves as a migration counter. Each version increment triggers onupgradeneeded for any client whose database version is behind. The migration code is idempotent: it checks whether each store or index already exists before creating it.
example.typescript
// Version 1: Initial schema
request.onupgradeneeded = (event) => {
const db = request.result;
if (event.oldVersion < 1) {
db.createObjectStore("users", { keyPath: "id", autoIncrement: true });
}
// Version 2: Add posts store + email index
if (event.oldVersion < 2) {
const posts = db.createObjectStore("posts", { keyPath: "id", autoIncrement: true });
posts.createIndex("authorId", "authorId", { unique: false });
const users = event.target.transaction.objectStore("users");
users.createIndex("email", "email", { unique: true });
}
// Version 3: Add sessions store with TTL index
if (event.oldVersion < 3) {
const sessions = db.createObjectStore("sessions", { keyPath: "token" });
sessions.createIndex("expiresAt", "expiresAt", { unique: false });
}
};
The event.oldVersion lets you branch on which migrations to run. If a client skips from version 1 to 3, all intermediate migrations execute in order within the same onupgradeneeded handler. This guarantees every client converges to the same schema.
Warning
Never change the schema inside a regular transaction. Schema mutations (createStore, createIndex, deleteStore) are only allowed in the onupgradeneeded callback. If you need to add an index at runtime, you must bump the version number and restart the connection.
3 · Data Model — Object Stores & Indexes
IndexedDB is a document database, not a relational one. There are no tables, rows, or SQL. Instead, you define object stores — collections of objects keyed by a primary key — and indexes that provide fast lookups on specific properties.
Figure 2 — Object store with auto-increment primary key and two secondary indexes. Index entries map indexed values back to primary keys for fast lookup.
Primary keys
Every object store must have a primary key, which can be:
Inline key path: A property of the object, e.g., { keyPath: "id" }. The object must contain an id property, which must be unique.
Auto-increment:{ keyPath: "id", autoIncrement: true }. IndexedDB assigns a monotonically increasing integer. If the object does not include the key property, one is added automatically.
Out-of-line key:{ autoIncrement: true } (no keyPath). The key is passed separately in store.put(value, key). Use this for custom key schemes.
Indexes — the key to fast queries
Without an index, the only way to find records is a full scan of the object store — O(n). Indexes maintain a sorted B-tree on a specified property, enabling O(log n) lookups. Each index entry maps an indexed value to the primary key of the matching record.
Indexes can be:
Unique: No two records can have the same value for the indexed property. Attempting to insert a duplicate triggers a transaction abort. Email addresses are a classic use case.
Multi-entry: When the indexed property is an array, each array element gets its own index entry. This lets you query for records containing a specific tag in a tags array.
Compound: Not natively supported, but you can create a synthetic key by combining properties into a single string or array before storing.
Note
Indexes are not free. Each index adds write overhead — every put() or delete() updates every index on that store. If a store has 5 indexes, a single write makes at least 6 B-tree mutations (1 for the store, 5 for the indexes). For write-heavy workloads, keep indexes to a minimum.
4 · Interface Definition (API)
The raw IndexedDB API is event-based and verbose. In production, you almost never use it directly — you wrap it. Here is the generic storage wrapper I use as the foundation for every IndexedDB-backed service.
The raw IDBRequest API uses DOM events (onsuccess, onerror) that do not compose well. A wrapper converts every request into a Promise, enabling async/await, error handling with try/catch, and composition with other async primitives. The idb library by Jake Archibald is the de-facto standard promisified wrapper, but the wrapper above is simple enough to implement in-house and avoid a dependency.
Key design decisions
Generic type parameter:IndexedDBStorage<T> infers the record type. The constraint extends { id: IDBValidKey } ensures every record has a valid primary key.
Lazy connection: The database connection is opened on the first call. Calling connect() explicitly lets the consumer handle the loading state.
No caching layer: Every read hits the disk. For hot data, add an in-memory LRU cache on top (see Performance section).
5 · Deep Dive — Transactions & Cursors
Two concepts define the IndexedDB developer experience: transactions and cursors. Getting them right is the difference between a reliable storage layer and a source of subtle race conditions.
Transaction lifecycle
A transaction in IndexedDB follows a strict lifecycle: create, activate, perform operations, commit or abort. Understanding this lifecycle is critical because the API does not expose an explicit commit() — the transaction auto-commits when the browser decides it is done.
Figure 3 — IndexedDB transaction lifecycle. Every transaction is either "readonly" or "readwrite". It auto-commits on completion or aborts on error.
Transactions are scoped to one or more object stores and have a mode: "readonly" (concurrent, no conflicts) or "readwrite" (exclusive lock on the store). A "readwrite" transaction blocks other readwrite transactions on the same stores until it completes.
A common pitfall: the transaction object is alive only while there are pending requests. Once all requests resolve and control returns to the event loop, the transaction auto-commits. If you try to use a transaction after a microtask boundary (e.g., insidesetTimeout or a chained Promise), you get an InvalidStateError.
Cursor-based pagination
IndexedDB has no SQL-like OFFSET and LIMIT. To paginate, you use a cursor — a pointer that iterates over the sorted index or store in a specified direction.
Figure 4 — Cursor-based pagination. IndexedDB has no OFFSET/LIMIT. Instead, create a key range and advance the cursor, collecting records until the page size is reached.
The key insight: cursor pagination is stable even when records are inserted or deleted between pages, unlike offset pagination which can skip or duplicate records. This makes cursor-based pagination the correct choice for IndexedDB.
Bulk operations
Writing records one at a time in separate transactions is slow — each transaction incurs disk sync overhead. Batch multiple writes into a single transaction for an order-of-magnitude speedup.
example.typescript
async function bulkWriteUsers(
db: IDBDatabase,
users: User[],
): Promise<void> {
const tx = db.transaction("users", "readwrite");
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
const store = tx.objectStore("users");
for (const user of users) {
store.put(user);
// No await — requests queue on the transaction
}
// Transaction commits when all requests complete
});
}
// Batch delete with cursor (avoids large in-memory key array)
async function deleteByRole(
db: IDBDatabase,
role: string,
): Promise<number> {
const tx = db.transaction("users", "readwrite");
const index = tx.objectStore("users").index("role");
const range = IDBKeyRange.only(role);
const cursor = index.openCursor(range);
let deleted = 0;
return new Promise((resolve, reject) => {
cursor.onsuccess = () => {
const c = cursor.result;
if (c) {
c.delete();
deleted++;
c.continue();
} else {
resolve(deleted);
}
};
cursor.onerror = () => reject(cursor.error);
});
}
The pattern is: create one transaction, issue all requests against it without individually awaiting each, then wait for tx.oncomplete. The requests queue on the transaction and the browser batches the disk writes.
6 · Data Flow — Read & Write Paths
Let's trace a complete write operation through the stack, from the app layer down to disk.
App calls storage.set(user)
The wrapper creates a readwrite transaction scoped to the 'users' store.
Transaction becomes active
The browser acquires an exclusive lock on the 'users' store. Other readwrite transactions on the same store are queued.
store.put(user) fires IDBRequest
The object serializes the value via the structured clone algorithm. The primary key is generated (auto-increment) or validated.
Index entries updated
For each index on the store, the indexed property is extracted and an entry is inserted into the index B-tree.
Data written to disk (SQLite)
The browser's storage backend writes the updated B-tree pages to the SQLite WAL (Write-Ahead Log). At this point the write is durable.
Transaction completes
The oncomplete callback fires. The Promise resolves with the new key. The caller receives the result.
The read path is similar but simpler: open a readonly transaction, resolve the primary key in the store B-tree (or the index B-tree for indexed lookups), deserialize the value, and return it. No disk write, no index mutation, no lock contention.
7 · Performance Optimization
IndexedDB performance varies wildly depending on how you use the API. These optimizations separate a fast storage layer from a slow one.
Batch writes in a single transaction
Writing 100 records in 100 separate transactions is ~100x slower than writing them in one transaction. Each transaction syncs the WAL to disk. Batching amortizes the sync cost. Use the bulk write pattern shown in the deep dive section.
Use getAll() instead of cursor for small result sets
If you expect fewer than ~100 results and you need all of them, store.getAll() returns an array directly without cursor iteration overhead. For larger sets, use a cursor to avoid allocating a huge array.
In-memory cache layer
Pages that read the same records repeatedly (e.g., a document editor loading the same paragraphs) benefit from an in-memory LRU cache in front of IndexedDB. The cache intercepts reads before they reach the disk. Use the same LRU cache pattern from the Autocomplete article — a Map-based cache with bounded size.
Avoid large object stores
A single object store with 100,000 records is slower for index lookups than splitting into domain-specific stores with fewer records each. IndexedDB is not a single-table SQL database. Design stores around access patterns, not normalized relations.
Storage quota monitoring
The browser allocates storage per origin. You can estimate usage and quota via the Storage API. Monitor this and warn the user before writes fail.
example.typescript
async function estimateQuota(): Promise<{ usage: number; quota: number }> {
if (!navigator.storage?.estimate) {
return { usage: 0, quota: 0 };
}
const estimate = await navigator.storage.estimate();
return {
usage: estimate.usage ?? 0,
quota: estimate.quota ?? 0,
};
}
async function isQuotaExceeded(thresholdPercent = 90): Promise<boolean> {
const { usage, quota } = await estimateQuota();
if (quota === 0) return false;
return (usage / quota) * 100 > thresholdPercent;
}
// Usage: warn user before write if storage is nearly full
async function safeWrite<T>(writeFn: () => Promise<T>): Promise<T> {
const nearFull = await isQuotaExceeded(85);
if (nearFull) {
console.warn("Storage nearly full — attempting write anyway");
}
try {
return await writeFn();
} catch (err) {
if (err instanceof DOMException && err.name === "QuotaExceededError") {
// Trigger cleanup or show UI prompt
throw new Error("Storage quota exceeded — please free up space");
}
throw err;
}
}
Tradeoff table
Strategy
Pros
Cons
Separate transactions per operation
Simple, easy to reason about
Slow for batch writes, higher lock contention
Batched transaction (chosen)
~10-100x faster for bulk writes
Larger transaction failure surface
No in-memory cache
Always consistent, no cache invalidation
Every read hits disk (asynchronous but slower)
LRU cache on top (chosen for hot paths)
Sub-millisecond reads for cached data
Stale data risk, cache invalidation logic needed
Cursor pagination (chosen)
Stable under insert/delete, O(log n) advance
No random-access "page 5"
8 · Security Considerations
IndexedDB is sandboxed by origin — a different origin cannot read your data — but a few attack surfaces remain.
XSS escalates to full data exfiltration: If an attacker injects a script into your page, they have full read/write access to the origin's IndexedDB. There is no per-database authentication. The only defense is preventing XSS in the first place — strict CSP headers, input sanitization, and no dangerouslySetInnerHTML.
Sensitive data in IndexedDB: Data is stored unencrypted on disk. On a shared device, another user with filesystem access could read it. Do not store plaintext passwords, tokens, or PII in IndexedDB without encryption. Consider the Web Crypto API for client-side encryption before storage.
Private browsing: Some browsers (Firefox, Safari) disable IndexedDB in private mode or clear it when the private window closes. The indexedDB.open() call may throw a SecurityError. Always wrap the open call in a try/catch and fall back to in-memory storage.
Storage quota as DoS vector: A malicious script could fill the origin's storage quota, preventing legitimate data from being written. The browser enforces per-origin quotas, but a compromised page can exhaust its own quota. Monitor remaining quota and alert the user.
Timing attacks on indexes: The duration of an indexed lookup reveals whether a value exists. For privacy-sensitive applications (e.g., a contact search), the timing difference between a cache hit and a miss could leak information. Consider constant-time lookups for sensitive data.
Warning
IndexedDB does not encrypt data at rest. If you store authentication tokens, API keys, or personally identifiable information, encrypt them before writing and decrypt after reading. Use the Web Crypto API with a key derived from a user-provided passphrase or stored in a secure context.
9 · Testing Strategy
IndexedDB tests have a unique challenge: the API is asynchronous and stateful. Tests must clean up the database between runs to avoid cross-test pollution.
Write and read a record: Insert an object, retrieve it by primary key, verify properties match. This tests the entire serialization → storage → deserialization pipeline.
Unique index constraint: Insert two records with the same indexed value and verify the transaction aborts. This tests the index uniqueness enforcement.
Index query returns correct record: Query by an indexed property and verify the returned record has the correct primary key and data.
Cursor pagination yields correct page: Insert N records, paginate with a cursor, verify page size and the nextCursor value.
Transaction rollback on error: Write one valid record and one invalid record (duplicate unique key) in the same transaction. Verify neither record was persisted — the transaction rolled back atomically.
Schema migration: Open a database at version 1, close it, reopen at version 2 with a new store, verify the new store exists and old data is intact.
Note
Use the idb library in tests for ergonomic syntax, even if the production code uses a custom wrapper. The library's deleteDB() function reliably removes databases between test runs, which is harder to do with the raw API. For Node.js environments, use fake-indexeddb — a pure-JS in-memory implementation of the IndexedDB API.
10 · Accessibility
IndexedDB is an API, not a UI component, so accessibility considerations are different from visual components. The focus is on resilience and user control.
Storage quota UI
When the storage quota is approaching the limit, the app should show a clear, non-technical message: "Storage is nearly full. Free up space by clearing old data." Provide a button or action to clear cached data. Do not silently fail writes — the user needs to know why their data is not being saved.
Offline fallback announcements
If the app uses IndexedDB for offline support, announce the offline/online status changes via a role="status" live region. Screen reader users must know when the app has gone offline and when data is being synced.
Loading states
IndexedDB operations are asynchronous. Every UI state that depends on IndexedDB data must handle loading, empty, and error states. Show a skeleton or spinner during initial load, not a blank page. If the database fails to open, show an actionable error message rather than a silent failure.
11 · Key Takeaways
IndexedDB is a document database, not SQL. Design object stores around your access patterns, not normalized relations. Each store is a collection of objects with a primary key and optional indexes.
Always wrap the raw API. The event-based IDBRequest does not compose. A thin Promise wrapper turns it into idiomatic async/await code and makes error handling consistent.
Batch writes in a single transaction. Multiple small transactions are orders of magnitude slower than one large transaction. The disk sync cost is per transaction, not per operation.
Use cursors for pagination, not offset. IndexedDB has no OFFSET/LIMIT. Cursor-based pagination is stable under concurrent writes and avoids the "skip/duplicate" problem.
Version number is your migration counter. Each schema change increments the version. The onupgradeneeded handler runs all intermediate migrations, guaranteeing every client converges to the same schema.
Monitor quota and handle errors gracefully. The Storage API tells you how much space is left. Catch QuotaExceededError and give the user a way to free space. Never fail silently.
IndexedDB is not encrypted at rest. Never store plaintext secrets. Use the Web Crypto API for client-side encryption, and always sanitize input to prevent XSS from escalating to full data access.
IndexedDB is the most powerful storage primitive available in the browser. It is not the simplest — that honor goes to localStorage — but it is the only one that combines structured data, indexed queries, transactions, and gigabyte-scale capacity. Every offline-first app, every rich-document editor, and every client-side cache is built on this foundation. Understanding its data model, transaction lifecycle, and cursor mechanics is essential for any frontend engineer building at scale.