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