Open History to see the last commit
1# @tanstack/browser-db-sqlite-persistence
2
3Browser SQLite persistence for TanStack DB using `wa-sqlite` + OPFS.
4
5Start with the [SQLite Persistence guide](../../docs/guides/sqlite-persistence.md) for Collection setup and lifecycle behavior.
6
7Supports both single-tab (default) and multi-tab usage. Multi-tab coordination
8is opt-in by passing a `BrowserCollectionCoordinator`.
9
10## Public API
11
12- `createBrowserWASQLitePersistence(...)`
13- `openBrowserWASQLiteOPFSDatabase(...)`
14- `BrowserCollectionCoordinator`
15- `persistedCollectionOptions(...)` (re-exported from core)
16
17## Quick start (single-tab)
18
19By default, `createBrowserWASQLitePersistence` uses `SingleProcessCoordinator`
20semantics — no leader election, no `BroadcastChannel`, no Web Locks. This is
21the right choice when your app is only ever open in one tab at a time, or when
22each tab uses its own database.
23
24```ts
25import { createCollection } from '@tanstack/db'
26import {
27 createBrowserWASQLitePersistence,
28 openBrowserWASQLiteOPFSDatabase,
29 persistedCollectionOptions,
30} from '@tanstack/browser-db-sqlite-persistence'
31
32type Todo = {
33 id: string
34 title: string
35 completed: boolean
36}
37
38const database = await openBrowserWASQLiteOPFSDatabase({
39 databaseName: `tanstack-db.sqlite`,
40})
41
42const persistence = createBrowserWASQLitePersistence({
43 database,
44})
45
46export const todosCollection = createCollection(
47 persistedCollectionOptions<Todo, string>({
48 id: `todos`,
49 getKey: (todo) => todo.id,
50 persistence,
51 schemaVersion: 1, // Per-collection schema version
52 }),
53)
54```
55
56## Multi-tab usage
57
58To safely share a single OPFS database across multiple tabs of the same
59origin, pass a `BrowserCollectionCoordinator` via the `coordinator` option.
60The coordinator uses the Web Locks API to elect a leader tab, and
61`BroadcastChannel` to fan out committed transactions to follower tabs.
62Follower tabs forward writes to the leader via RPC over the channel.
63
64```ts
65import { createCollection } from '@tanstack/db'
66import {
67 BrowserCollectionCoordinator,
68 createBrowserWASQLitePersistence,
69 openBrowserWASQLiteOPFSDatabase,
70 persistedCollectionOptions,
71} from '@tanstack/browser-db-sqlite-persistence'
72
73const database = await openBrowserWASQLiteOPFSDatabase({
74 databaseName: `tanstack-db.sqlite`,
75})
76
77const coordinator = new BrowserCollectionCoordinator({
78 dbName: `tanstack-db`,
79})
80
81const persistence = createBrowserWASQLitePersistence({
82 database,
83 coordinator,
84})
85
86export const todosCollection = createCollection(
87 persistedCollectionOptions<Todo, string>({
88 id: `todos`,
89 getKey: (todo) => todo.id,
90 persistence,
91 schemaVersion: 1,
92 }),
93)
94
95// On teardown:
96// coordinator.dispose()
97// await database.close?.()
98```
99
100See [`examples/react/offline-transactions`](../../examples/react/offline-transactions/src/db/persisted-todos.ts)
101for a full multi-tab example.
102
103### Committed transaction ownership
104
105The persisted sync wrapper sends every source transaction with durable effects
106through the coordinator's required
107`requestApplyCommittedTx(collectionId, tx)` method.
108`BrowserCollectionCoordinator` routes the complete transaction to the current
109leader for that collection. The leader applies it with the adapter registered
110for the same collection id, including that collection's resolved mode and
111`schemaVersion`.
112
113The route preserves truncation, row changes, row metadata, collection metadata,
114and stream position as one `PersistedTx`. It does not feature-detect a partial
115route or fall back to row-only mutation RPC. A custom coordinator that omits
116`requestApplyCommittedTx` is rejected while the collection is configured,
117before its sync source can publish rows. An effect-free source commit neither
118publishes nor consumes a coordinator sequence.
119
120Single-tab mode uses the same complete transaction contract. Its
121`SingleProcessCoordinator` skips election and channel traffic but still routes
122the transaction to the resolved adapter for that collection.
123
124If a mutating RPC loses its response, Browser coordination replays it only
125while the requester still knows the same non-null leader id and term. An
126unknown initial route or any leader/term change rejects with
127`IndeterminateCommitError`. The coordinator does not retry that mutation
128against an unknown or replacement leader. Direct mutation callers must
129reconcile the outcome.
130
131For a source sync transaction, the persisted wrapper keeps its applied receipt
132pending while the replacement leader checks the exact transaction ID in SQLite
133under the writer lock. If the ID is present, the receipt fulfills and peers
134reload any committed rows they missed. If the ID is absent and the durable row
135version and reset epoch still match the pre-send snapshot, the replacement
136applies that transaction once and the receipt fulfills. The Collection and its
137dependent live queries stay in the same sync run. If another write, reset, or
138pruning makes the outcome unsafe to certify, the receipt rejects with the
139original `IndeterminateCommitError` and the source run enters error. This
140reconciliation applies only when both the coordinator and adapter provide the
141exact-ID operation; it does not change direct RPC behavior. Tabs running an
142older protocol version do not participate in this same-run recovery contract.
143
144### Remote subset requests
145
146`BrowserCollectionCoordinator.requestEnsureRemoteSubset(...)` validates and
147projects the request before it chooses the local leader or `BroadcastChannel`
148route. Registered owners receive the exported
149`TransportedLoadSubsetOptions` type. It contains the supported
150structured-clone wire data and excludes live `signal` and `subscription`
151fields. Unsupported nested values fail immediately with
152`RemoteSubsetWireValueError` and the exact value path; no owner callback or
153channel post occurs. See the core package's remote subset wire contract for the
154complete supported domain.
155
156Each accepted request is an explicit lease. Retries of the same request object
157reuse its acquisition identity, while distinct equal request objects remain
158independent. Release is routed to the elected collection owner and unloads the
159exact acquired options once. Leadership loss unloads the retiring owner's live
160leases, and requesters replay still-live acquisitions against the next leader.
161Registering a second owner for one collection throws
162`DuplicateRemoteSubsetOwnerError`; no adapter fallback replaces the owner.
163Remote follower transport/admission failures reject and retain demand for its
164normal retry without entering the follower's local owner lifecycle. Terminal
165release identities expire after the existing RPC dedupe horizon while delayed
166duplicates inside that horizon remain idempotent.
167
168## Notes
169
170- `openBrowserWASQLiteOPFSDatabase(...)` starts a dedicated Web Worker and
171 routes SQL operations through it. OPFS sync access handle APIs are used in
172 that worker context.
173- Opening has a 30-second deadline by default. `timeoutMs` changes it; `0`
174 explicitly disables the deadline. A timed-out open rejects with
175 `TimeoutError` and terminates its pending worker, so it cannot acquire the
176 database later. Pass an `AbortSignal` to cancel earlier; the signal applies
177 only while opening, not to the established connection.
178- On `pagehide`, the connection terminates its worker synchronously and rejects
179 pending initialization, queries, and close operations with `AbortError`. This
180 also applies when the document enters the back/forward cache. Applications
181 restored through
182 `pageshow` with `event.persisted` must create fresh database connections and
183 persistence/collection instances (or reload the application).
184- Flush application writes and await `database.close()` before navigating when
185 possible. The `pagehide` cleanup releases resources; it cannot await pending
186 writes or serve as a durability guarantee.
187- Single-tab mode does not require `BroadcastChannel` or Web Locks for
188 election, but committed transactions still go through the collection's
189 registered persistence owner.
190- Multi-tab mode requires `BroadcastChannel` and the Web Locks API; both are
191 available in all modern browsers.
192- OPFS capability failures are surfaced as `PersistenceUnavailableError`.
193- SQLite open failures include the underlying VFS error name and message when
194 wa-sqlite exposes them. Some failures, including native access-handle
195 contention, are not currently exposed by wa-sqlite and retain SQLite's
196 generic open error.