Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

README.md

233 lines10.1 KB

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
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 }),
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 }),
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. The package includes the worker and a separate
173 `wa-sqlite.wasm` asset. Vite, webpack 5, and Next.js with Turbopack or
174 webpack include both automatically, with no asset copying or WASM URL
175 configuration required.
176- In Vite development, a pre-bundled copy of this package asks the dev server
177 for its assets by package name, from the app root. Production builds drop
178 this lookup:
179 - If the app reaches the package only through another library or through an
180 npm alias, the root cannot resolve that name. The open rejects with
181 `PersistenceUnavailableError`.
182 - If more than one copy is installed, the pre-bundled copy loads the assets
183 of the copy that the root resolves. When that copy is another version, its
184 worker refuses the opener and the open rejects with
185 `PersistenceUnavailableError`.
186 - The copy finds the dev server through the page's Vite client script. If
187 the database opens inside a worker, or the page loads the Vite client
188 without a script `src`, the copy cannot find its assets and the open
189 rejects with `PersistenceUnavailableError`.
190​
191 In those cases, exclude the package from pre-bundling so Vite serves it
192 beside its own assets. List the name that the importing code uses, which is
193 the alias name for an npm alias:
194​
195 ```ts
196 // vite.config.ts
197 export default defineConfig({
198 optimizeDeps: {
199 exclude: [`@tanstack/browser-db-sqlite-persistence`],
200 },
201 })
202 ```
203​
204- Opening has a 30-second deadline by default. `timeoutMs` changes it; `0`
205 explicitly disables the deadline. A timed-out open rejects with
206 `TimeoutError` and terminates its pending worker, so it cannot acquire the
207 database later. Pass an `AbortSignal` to cancel earlier; the signal applies
208 only while opening, not to the established connection.
209- On `pagehide`, the connection terminates its worker synchronously and rejects
210 pending initialization, queries, and close operations with `AbortError`. This
211 also applies when the document enters the back/forward cache. Applications
212 restored through
213 `pageshow` with `event.persisted` must create fresh database connections and
214 persistence/collection instances (or reload the application).
215- `database.close()` stops accepting requests when it starts; later calls to
216 `execute` reject with `SQLiteConnectionClosedError`, and concurrent `close()` calls share one outcome. The
217 worker finishes queries submitted before close, in order, and then closes,
218 so those queries keep their results. Close can therefore wait while another
219 tab holds the database's OPFS access handle. If `pagehide` or a worker
220 failure ends the connection first, queries still pending reject.
221- Flush application writes and await `database.close()` before navigating when
222 possible. The `pagehide` cleanup releases resources; it cannot await pending
223 writes or serve as a durability guarantee.
224- Single-tab mode does not require `BroadcastChannel` or Web Locks for
225 election, but committed transactions still go through the collection's
226 registered persistence owner.
227- Multi-tab mode requires `BroadcastChannel` and the Web Locks API; both are
228 available in all modern browsers.
229- OPFS capability failures are surfaced as `PersistenceUnavailableError`.
230- SQLite open failures include the underlying VFS error name and message when
231 wa-sqlite exposes them. Some failures, including native access-handle
232 contention, are not currently exposed by wa-sqlite and retain SQLite's
233 generic open error.