fast-idb
v0.3.1
Published
Typed IndexedDB CRUD store factory with optional React/Zustand integration, and declared databases with atomic multi-store writes
Maintainers
Readme
fast-idb
Ultra-simple, typed IndexedDB CRUD. Just collection<T>('name') and go.
Optional React + Zustand integration included. For apps that sync or must not
lose writes, fast-idb/db opens declared,
versioned databases with atomic writes across stores.
Install
bun add fast-idb
# peer dep (optional — only if you use fast-idb/react):
# zustand >= 4.0Quick Start
import { collection } from 'fast-idb'
interface Todo {
id: string
title: string
done: boolean
createdAt: string
updatedAt: string
}
const todos = collection<Todo>('todos')
// Create — id + timestamps are auto-generated
await todos.create({ title: 'Buy milk', done: false })
// Read
await todos.get('some-id')
await todos.getAll()
await todos.getAll({ direction: 'desc', limit: 10 })
// Update — merges fields, updates updatedAt
await todos.update('some-id', { done: true })
// Delete
await todos.delete('some-id')
// Bulk
await todos.bulkCreate([{ title: 'A', done: false }, { title: 'B', done: true }])
await todos.bulkPut(importedTodos)
await todos.bulkDelete(['id-1', 'id-2'])
// Filter / Find
await todos.filter(t => t.done === true)
await todos.find(t => t.title.includes('milk'))
// Count / Clear
await todos.count()
await todos.clear()That's it. No database config, no version management, no setup. The library handles everything internally:
- Single shared IndexedDB database
- Object stores created on demand — every collection declared before the first read is created in one upgrade
- Auto-generated IDs (timestamp + sequence + random) that sort in creation order, so key order is creation order;
createnever overwrites an existing record - Yields to upgrades from other tabs and reconnects on its own
- Auto-managed
createdAt/updatedAttimestamps
With React + Zustand
// db.ts
import { collection } from 'fast-idb'
import { createCrudStore } from 'fast-idb/react'
import { toast } from 'sonner'
interface Todo {
id: string
title: string
done: boolean
createdAt: string
updatedAt: string
}
const todos = collection<Todo>('todos')
export const useTodos = createCrudStore(todos, {
sortDirection: 'desc',
labels: { entity: 'Todo' },
toast: (type, title, desc) => toast[type](title, { description: desc }),
})// TodoList.tsx
import { useEffect } from 'react'
import { useTodos } from './db'
export function TodoList() {
const { items, isLoading, fetchAll, create, remove } = useTodos()
useEffect(() => { fetchAll() }, [])
if (isLoading) return <p>Loading...</p>
return (
<div>
<button onClick={() => create({ title: 'New todo', done: false })}>
Add Todo
</button>
<ul>
{items.map(t => (
<li key={t.id}>
{t.title}
<button onClick={() => remove(t.id)}>x</button>
</li>
))}
</ul>
</div>
)
}Collection API
| Method | Description |
|---|---|
| name | The object store's name |
| get(key) | Get one record |
| getAll(options?) | Get all, with optional direction/limit/offset, in one transaction |
| count() | Count records |
| create(data) | Create (auto ID + timestamps); fails rather than overwrite |
| update(key, data) | Partial merge update, read and written in one transaction |
| put(item) | Full upsert (no merge) |
| delete(key) | Delete by key |
| clear() | Delete all records |
| bulkCreate(items) | Batch create; returns { succeeded, failed, created }, including generated ids and timestamps |
| bulkPut(items) | Batch upsert in one transaction |
| bulkDelete(keys) | Batch delete in one transaction |
| forEach(cb, options?) | Visit records in key order; cb may be async |
| find(predicate, options?) | First match; stops reading there |
| filter(predicate, options?) | All matches |
forEach snapshots the keys selected by the query before the first callback,
then reads their records 100 per transaction. A callback can await anything;
its return value is ignored. Each page is a consistent read. New keys are not
visited, including when imported records have custom IDs. Records deleted
before their page is read are skipped, and updates made before that read are
visible. The selected key list stays in memory for the duration of the walk;
record values are loaded one page at a time.
find and filter take synchronous predicates and read in one transaction,
100 records per request; find stops at the first match.
Query Options
await todos.getAll({ direction: 'desc', limit: 10, offset: 5 })| Option | Type | Default | Description |
|---|---|---|---|
| direction | 'asc' \| 'desc' | 'asc' | Sort order |
| limit | number | no limit | Max results |
| offset | number | 0 | Skip N results |
limit and offset must be numbers >= 0 (fractions are rounded down);
anything else throws a RangeError. A limit of Infinity or above 2^32-1
means no limit; an offset of Infinity returns nothing. Large finite offsets
are advanced in steps within the browser's cursor count range. getAll,
find and filter locate pages with key cursors and read values in batches.
Zustand Store API (fast-idb/react)
| Property/Method | Description |
|---|---|
| items | Loaded records, narrowed by the active search |
| allItems | Every loaded record, in sort order |
| isLoading | True while any fetchAll runs |
| isSubmitting | True while any create, update or remove runs |
| hasFetched | True after first fetch |
| error | Error message or null |
| fetchAll() | Load all from DB |
| create(data) | Create + add to items in sort order |
| update(key, data) | Update + sync items; returns the record, rejects if missing |
| remove(key) | Delete + remove from items; resolves true, rejects if missing |
| getOne(key) | Read single item |
| search(predicate, query?) | Show matching loaded records, also without a query; an explicit empty query shows all. Stays applied to later changes |
| searchPredicate | The active search's predicate, or null |
| clearSearch() | Show every loaded record again (no database read) |
| setItems(items) | Replace the loaded records; the active search still applies |
| openDialog(name, item?) | Open named dialog |
| closeDialog(name) | Close named dialog |
| selectedItem | Item selected via openDialog |
| refresh() | Re-fetch everything |
With a limit or offset in queryOptions, the store holds a window of the
records, and create and remove re-read that window so it matches the next
fetchAll.
Declared databases (fast-idb/db)
collection() creates its stores on demand in one shared database. When an
app needs a declared schema, one database per account, or writes to several
stores that must commit together, such as an offline outbox beside the records
it changes, use fast-idb/db. It leaves collection() and fast-idb/react
unchanged.
import { openDatabase, prefix } from 'fast-idb/db'
interface Row { scope: string; entity: string; id: string; rev: number; refs: string[] }
interface Op { seq?: number; operationId: string; command: string }
const db = await openDatabase<{ records: Row; outbox: Op; meta: unknown }>({
name: `school:${accountId}`,
version: 1,
stores: {
records: {
key: ['scope', 'entity', 'id'],
indexes: { byRef: { path: 'refs', multiEntry: true } },
},
outbox: {
key: 'seq',
autoIncrement: true,
indexes: { byOperation: { path: 'operationId', unique: true } },
},
meta: {},
},
})
// One transaction: every op commits, or none does.
await db.write([
{ add: 'outbox', value: { operationId, command: 'student.update' } },
{ put: 'meta', key: 'lastSave', value: Date.now() },
], { durability: 'strict', tags: ['students'] })
// A downloaded page: only revisions newer than the stored ones replace them.
await db.write([
...page.map((value) => ({ putIfNewer: 'records' as const, value, revision: 'rev' })),
{ put: 'meta', key: 'cursor', value: next },
])
await db.getAll('records', prefix(['2025-2026', 'student']))
await db.getAllFromIndex('records', 'byRef', '2025-2026|section:a')
await db.deleteWhere('records', 'byRef', '2025-2026|class:cp')
db.onCommit(({ tags, local }) => {
// Invalidate cached queries; `local` is false for commits from other tabs.
})| Member | Description |
|---|---|
| write(ops, options?) | put, add, putIfNewer, delete and clear across stores in one transaction, in order; resolves { key, written } per op after the commit |
| read(stores, fn) | One read-only transaction across stores: no commit lands between its requests |
| transaction(stores, fn, options?) | A read-write transaction for logic write cannot express |
| get, getAll, getAllKeys, count | One-off reads by key, key range or prefix() |
| getAllFromIndex, getAllKeysFromIndex, countFromIndex | Reads through an index |
| deleteWhere(store, index, query, options?) | Delete what an index query selects; resolves how many records |
| onCommit(listener) | After each commit that wrote, here or in another tab or worker; returns an unsubscribe function |
| close(), closed | Close the connection |
Writes that commit together
write queues every op in one transaction without awaiting anything else in
between, so IndexedDB cannot commit part of a batch: a duplicate key, a value
that cannot be cloned or a full disk rolls all of it back. durability: 'strict'
asks the browser to reach disk before reporting the commit, where supported.
putIfNewer reads the stored record and writes only when the new value's
revision is greater. Revisions compare as IndexedDB keys: numbers, strings or
arrays such as [position, sequence]. A newer deletion marker therefore keeps
an older page from bringing a record back. Ops keep their order, including
around conditional puts.
Concurrent tx.putIfNewer calls for the same store and key also wait for each
other, so Promise.all keeps the newest revision even with duplicate keys.
Inside read and transaction, await only the transaction's own requests.
Awaiting anything else, such as a fetch or a timer, lets IndexedDB commit what
was queued so far, and the next request fails with an 'inactive' error.
Writes that already committed still trigger onCommit, even if the callback
later fails.
Keys and indexes
key is a property name, a dotted path, or an array of them for a compound
key. Without key, writes pass the key beside the value
({ put: 'meta', key: 'cursor', value }). autoIncrement keys increase in
commit order across every tab and worker. prefix(parts) selects the compound
keys that start with parts when the next component is not an array. Its upper
bound is [...parts, []]: arbitrary array-valued next components can fall
outside the range. For those keys, use an explicit range and filter as needed.
A multiEntry index lists a record under each
element of an array, so any of its references finds it; it needs a single key
path, so keep the scope inside the strings.
Versions, migrations and closing
await openDatabase({
name,
version: 3,
stores,
migrationTimeoutMs: 60_000, // optional; shared by all crossed migrations
migrations: {
3: async ({ tx }) => {
for (const row of await tx.getAll('records')) {
await tx.put('records', { ...row, refs: row.refs ?? [] })
}
},
},
onBlocked: () => askToCloseOtherTabs(),
onClose: (reason) => {
// 'closed' | 'versionchange' | 'deleted' | 'terminated'
},
})Raise version whenever the declared stores change. An upgrade creates missing
stores and indexes, rebuilds a changed index and drops an undeclared one. It
never drops a store, and refuses one whose key changed: move its records to a
store with a new name in a migration. Opening a database whose stores differ
from the declaration at the same version fails with 'schema'.
Migrations run in order inside the upgrade when an older database opens, never for a new one. Missing stores are available immediately; new and rebuilt indexes are created after the last migration. Migrations can use unchanged indexes, but cannot use indexes added or changed in this upgrade. This allows a migration to remove duplicates before a unique index is built, including when skipping versions.
The upgrade stays open across external awaits such as timers or Web Crypto.
All crossed migrations share a 60-second time limit; set migrationTimeoutMs
to an integer from 1 to 2,147,483,647 to change it. A failure or timeout rolls
the whole upgrade back: opening rejects with a 'migration' error and the
database keeps its previous version and data. A timeout stops the dummy reads
and releases waiting connections. It cannot cancel your external work; any late
transaction requests fail after the abort.
Keep external work short; pending upgrades hold connections and use dummy read
requests to stay alive. Migration requests go directly to IndexedDB when active;
only a synchronous TransactionInactiveError queues them for the next active
request event. For raw
structural changes through db, run them in the migration's initial call or
immediately after awaiting a tx request, while the upgrade is active.
When another tab upgrades or deletes the database,
this connection closes and later calls fail with 'closed'; open it again.
onBlocked reports a connection that does not close, such as an older tab,
holding the upgrade.
For the shared collection() database, a blocked upgrade rejects pending calls
with an error asking you to close other connections and retry. React fetches
record that error and clear isLoading. After closing the blocking connection,
call the operation again; the shared connection is reopened automatically.
Errors
Failures reject with a StorageError whose kind says what to do:
'unavailable', 'version' (a newer app already upgraded the database),
'schema', 'migration', 'closed', 'quota', 'constraint', 'data',
'inactive', 'aborted' or 'unknown'. cause holds the IndexedDB error.
Invalid arguments throw TypeError or RangeError before any transaction
starts, and an error thrown by your own transaction callback rejects unchanged.
More
factory: anIDBFactoryto use instead ofglobalThis.indexedDB. Tests can give each case a freshfake-indexeddbone. Importingfast-idb/dbtouches no browser global.broadcast: falsekeeps commit events inside this connection.deleteDatabase(name, { factory?, onBlocked? }), andlistDatabases({ prefix?, factory? }), which resolves null where the browser cannot list databases.persistStorage(),isStoragePersisted()andestimateStorage()wrapnavigator.storage.
Testing failures (fast-idb/testing)
import { injectFault } from 'fast-idb/testing'
injectFault(db, { store: 'outbox', op: 'add' }) // the next outbox add: QuotaExceededError
injectFault(db, { skip: 1 }) // the second write request
injectFault(db, { op: 'commit', error: 'UnknownError' }) // the commit itselfA fault fires once, on the next matching request of a fast-idb/db database,
and rolls its whole transaction back as a real failure would. injectFault
returns a function that removes the fault if it has not fired.
License
MIT
