Lesson 4 of 9 · 26m
IndexedDB: A Transactional Database, Not localStorage With Cancer
Object stores, indexes, cursors, and transaction lifetime — the IndexedDB mental model that prevents lost writes and corrupted offline state.
IndexedDB has a terrible reputation because its API is old enough to remember when callbacks were a lifestyle. Underneath that crust is a serious primitive: a transactional, indexed, client-side object database capable of storing megabytes or gigabytes of structured data and blobs. Treat it like a tiny database and it behaves. Treat it like a key-value bag with asynchronous timing and it will eat your offline queue.
Schema is explicit
const db = await new Promise((resolve, reject) => {
const req = indexedDB.open("field-ops", 3);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains("reports")) {
const store = db.createObjectStore("reports", { keyPath: "id" });
store.createIndex("byUpdatedAt", "updatedAt");
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});Version upgrades are the migration system. There is no runtime CREATE TABLE afterthought; if a store or index is missing, increment the version and write upgrade code. Users can be several versions behind, so migrations must chain, not assume last release.
Transactions have a lifetime
A transaction commits when control returns to the event loop with no pending requests. Await unrelated work in the middle and it can become inactive:
// Fragile: unrelated asynchronous work can end the transaction.
const tx = db.transaction("reports", "readwrite");
tx.objectStore("reports").put(report);
await fetch("/lookup");
tx.objectStore("reports").put(nextReport); // can throw TransactionInactiveError
// Better: prepare data first, then keep the transaction tight.
const tx = db.transaction("reports", "readwrite");
tx.objectStore("reports").put(report);
await new Promise((resolve, reject) => {
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});Native IndexedDB requests are event-target objects, not promises. Thin libraries such as idb make them awaitable, but the rule stands either way: IndexedDB transactions are not general async scopes.
Indexes answer access paths
Store records in primary-key order, but query through indexes for fields you filter on. A cursor can page through thousands of entries without materializing them all. Store blobs directly for images or files instead of base64-encoding them into strings; base64 inflates storage and destroys memory headroom.
Field notes
- Use
idbor a similarly thin promise wrapper; avoid heavyweight ORM abstractions until you know the underlying transaction rules. - Private browsing modes may evict or restrict storage. Treat persistence as best-effort unless
navigator.storage.persist()succeeds. - Never use IndexedDB as the only copy of irreplaceable user work without sync or export. Browser storage is user-managed storage.
- Migration failures are production incidents. Test upgrades from real old databases, not just empty installs.
Was this lesson helpful?