IndexedDB transactions that close behind your back
IndexedDB is the only real database built into every browser. It stores structured data, blobs, and far more than localStorage's few megabytes, and it works offline.
IndexedDB is the only real database built into every browser. It stores structured data, blobs, and far more than localStorage’s few megabytes, and it works offline. Most people use it through a small wrapper like idb, which turns its event-based API into promises.
The promises make it look like any other async code. That’s exactly where the trouble starts, because IndexedDB transactions have a rule that async/await makes very easy to break.
The rule
A transaction stays open only while it has work queued. Once your code hands control back to the event loop and there are no pending requests on the transaction, the browser commits it. You never call “commit”. It just happens.
Awaiting another IndexedDB request is fine, because the transaction still has something in flight. Awaiting anything else, like a fetch, a timer or a message from a worker, isn’t:
import { openDB } from 'idb';
const db = await openDB('shop', 1, {
upgrade(db) {
db.createObjectStore('cart', { keyPath: 'id' });
},
});
const tx = db.transaction('cart', 'readwrite');
const item = await tx.store.get(productId);
const price = await fetch(`/api/price/${productId}`).then((r) => r.json());
await tx.store.put({ ...item, price }); // throws: the transaction has finished
While the fetch was in flight, the transaction had nothing to do, so it committed. The put throws. In the worst case, the error is swallowed somewhere and the user’s change is simply never saved.
Do the slow work first
The fix is to keep transactions short and synchronous in spirit: gather everything you need, then open the transaction and only talk to the database inside it.
const price = await fetch(`/api/price/${productId}`).then((r) => r.json());
const tx = db.transaction('cart', 'readwrite');
const item = await tx.store.get(productId);
await tx.store.put({ ...item, price });
await tx.done; // resolves when the transaction has committed
That last line matters. A put resolving means the request succeeded, not that the data is safely written. tx.done resolves when the whole transaction commits, and rejects if it aborts.
If the read and the write really must be atomic across a network call, IndexedDB can’t do that for you. Read inside one transaction, do the network call, then write in a second transaction that checks the value hasn’t changed in between.
Upgrades without a migrations tool
IndexedDB has its own schema versioning. You open the database with a version number, and if it’s higher than what’s on disk, the upgrade callback runs. The neat pattern is a switch with fall-through, so a user coming from any old version runs every step they missed:
const db = await openDB('shop', 2, {
upgrade(db, oldVersion, newVersion, transaction) {
switch (oldVersion) {
case 0:
db.createObjectStore('cart', { keyPath: 'id' });
// falls through
case 1:
transaction.objectStore('cart').createIndex('byAdded', 'addedAt');
}
},
});
A brand new user starts at 0 and runs both steps. A user on version 1 runs only the second. Never edit an old case once it has shipped. Add a new one instead, exactly like database migrations on a server.
The tab you forgot about
Upgrades have one more catch. If the user has your app open in another tab, that tab holds a connection to the old version, and the upgrade can’t start until it closes. The new tab just waits.
idb exposes both sides of this:
const db = await openDB('shop', 3, {
upgrade(db, oldVersion) { /* ... */ },
// in the NEW tab: an old connection is in the way
blocked() {
showBanner('Please close other tabs of this app to finish updating.');
},
// in the OLD tab: someone wants a newer version
blocking() {
db.close();
showBanner('A new version is available. Reload to continue.');
},
});
The blocking handler is the important one. If every version of your app closes its connection when asked, upgrades never get stuck. Ship it from your very first version, before you need it.
Your data can still disappear
IndexedDB is durable, but not permanent. Browsers may clear it when the disk is low, and since 2020, Safari deletes script-writable storage, IndexedDB included, for sites the user hasn’t interacted with in seven days of browser use. Web apps added to the home screen are exempt.
You can ask for more protection:
if (navigator.storage?.persist) {
const persisted = await navigator.storage.persist();
console.log(persisted ? 'Storage is persistent' : 'Storage may be cleared');
}
const { usage, quota } = await navigator.storage.estimate();
The browser decides whether to grant it. Either way, the safe design is to treat IndexedDB as a fast local copy, not the only copy, and sync anything important to a server.
In short
- Inside a transaction, await only IndexedDB requests. Do network calls before or after.
- Await tx.done when you need to know the write actually happened.
- Version your schema with a fall-through switch on oldVersion.
- Close the connection in blocking(), from day one.
- Don’t treat browser storage as the only copy of anything that matters.