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 application must reconcile the outcome. The
128coordinator does not retry that mutation against an unknown or replacement
129leader.
130
131### Remote subset requests
132
133`BrowserCollectionCoordinator.requestEnsureRemoteSubset(...)` validates and
134projects the request before it chooses the local leader or `BroadcastChannel`
135route. Registered owners receive the exported
136`TransportedLoadSubsetOptions` type. It contains the supported
137structured-clone wire data and excludes live `signal` and `subscription`
138fields. Unsupported nested values fail immediately with
139`RemoteSubsetWireValueError` and the exact value path; no owner callback or
140channel post occurs. See the core package's remote subset wire contract for the
141complete supported domain.
142
143Each accepted request is an explicit lease. Retries of the same request object
144reuse its acquisition identity, while distinct equal request objects remain
145independent. Release is routed to the elected collection owner and unloads the
146exact acquired options once. Leadership loss unloads the retiring owner's live
147leases, and requesters replay still-live acquisitions against the next leader.
148Registering a second owner for one collection throws
149`DuplicateRemoteSubsetOwnerError`; no adapter fallback replaces the owner.
150Remote follower transport/admission failures reject and retain demand for its
151normal retry without entering the follower's local owner lifecycle. Terminal
152release identities expire after the existing RPC dedupe horizon while delayed
153duplicates inside that horizon remain idempotent.
154
155## Notes
156
157- `openBrowserWASQLiteOPFSDatabase(...)` starts a dedicated Web Worker and
158 routes SQL operations through it. OPFS sync access handle APIs are used in
159 that worker context.
160- Opening has a 30-second deadline by default. `timeoutMs` changes it; `0`
161 explicitly disables the deadline. A timed-out open rejects with
162 `TimeoutError` and terminates its pending worker, so it cannot acquire the
163 database later. Pass an `AbortSignal` to cancel earlier; the signal applies
164 only while opening, not to the established connection.
165- On `pagehide`, the connection terminates its worker synchronously and rejects
166 pending initialization, queries, and close operations with `AbortError`. This
167 also applies when the document enters the back/forward cache. Applications
168 restored through
169 `pageshow` with `event.persisted` must create fresh database connections and
170 persistence/collection instances (or reload the application).
171- Flush application writes and await `database.close()` before navigating when
172 possible. The `pagehide` cleanup releases resources; it cannot await pending
173 writes or serve as a durability guarantee.
174- Single-tab mode does not require `BroadcastChannel` or Web Locks for
175 election, but committed transactions still go through the collection's
176 registered persistence owner.
177- Multi-tab mode requires `BroadcastChannel` and the Web Locks API; both are
178 available in all modern browsers.
179- OPFS capability failures are surfaced as `PersistenceUnavailableError`.
180- SQLite open failures include the underlying VFS error name and message when
181 wa-sqlite exposes them. Some failures, including native access-handle
182 contention, are not currently exposed by wa-sqlite and retain SQLite's
183 generic open error.