Open History to see the last commit
1---
2title: SQLite Persistence
3id: sqlite-persistence
4---
5
6SQLite persistence stores Collection rows in a SQLite database supplied by the runtime. A new Collection can load those rows when it uses the same database. The wrapper can also save sync metadata so a supported sync adapter can resume safely.
7
8Choose a package for your runtime. Each runtime package supplies a SQLite driver and re-exports `persistedCollectionOptions` from `@tanstack/db-sqlite-persistence-core`.
9
10SQLite persistence stores Collection data. To retain mutations that still need a server response, use [offline transactions](./offline-transactions.md). The [combined React Native recipe](./offline-transactions.md#use-sqlite-persistence-with-the-outbox) shows both stores together.
11
12## Choose a runtime package
13
14Each package connects through its runtime's database, storage, or IPC interface. Follow its README for setup and required native plugins.
15
16| Runtime | Package and setup | Factory |
17| --- | --- | --- |
18| Browser with OPFS | [`@tanstack/browser-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/browser-db-sqlite-persistence#readme) | `createBrowserWASQLitePersistence` |
19| Node.js | [`@tanstack/node-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/node-db-sqlite-persistence#readme) | `createNodeSQLitePersistence` |
20| React Native with OP-SQLite | [`@tanstack/react-native-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/react-native-db-sqlite-persistence#readme) | `createReactNativeSQLitePersistence` |
21| Expo with `expo-sqlite` | [`@tanstack/expo-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/expo-db-sqlite-persistence#readme) | `createExpoSQLitePersistence` |
22| Capacitor | [`@tanstack/capacitor-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/capacitor-db-sqlite-persistence#readme) | `createCapacitorSQLitePersistence` |
23| Tauri | [`@tanstack/tauri-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/tauri-db-sqlite-persistence#readme) | `createTauriSQLitePersistence` |
24| Electron | [`@tanstack/electron-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/electron-db-sqlite-persistence#readme) | `createElectronSQLitePersistence` in a renderer |
25| Cloudflare Durable Objects (server) | [`@tanstack/cloudflare-durable-objects-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/cloudflare-durable-objects-db-sqlite-persistence#readme) | `createCloudflareDOSQLitePersistence` |
26
27The core package has no SQLite engine binding. Use a runtime package unless you are implementing a new driver.
28
29## Start in the browser
30
31Install the browser wrapper and its SQLite engine:
32
33```sh
34npm install @tanstack/db @tanstack/browser-db-sqlite-persistence @journeyapps/wa-sqlite
35```
36
37This example uses one browser tab. Open an OPFS database, then create one persistence instance for it. Give every persisted Collection a stable `id` and a `getKey` function. Set `schemaVersion` to track the stored row format. Increase it when that format changes.
38
39```ts
40import { createCollection } from '@tanstack/db'
41import {
42 createBrowserWASQLitePersistence,
43 openBrowserWASQLiteOPFSDatabase,
44 persistedCollectionOptions,
45} from '@tanstack/browser-db-sqlite-persistence'
46
47type Todo = {
48 id: string
49 title: string
50 completed: boolean
51}
52
53const database = await openBrowserWASQLiteOPFSDatabase({
54 databaseName: 'app.sqlite',
55})
56const persistence = createBrowserWASQLitePersistence({ database })
57
58const todos = createCollection(
59 persistedCollectionOptions<Todo, string>({
60 id: 'todos',
61 getKey: (todo) => todo.id,
62 persistence,
63 schemaVersion: 1,
64 }),
65)
66
67await todos.preload()
68const transaction = todos.insert({
69 id: '1',
70 title: 'Buy milk',
71 completed: false,
72})
73await transaction.when('settled')
74```
75
76This Collection has no `sync` option. Its normal insert, update, and delete handlers save local mutations to SQLite. It does not contact a server. The browser must support OPFS and run in a secure context. If multiple tabs can open the same database, use the [multi-tab setup](#browser-tabs-and-electron-renderers).
77
78### Manual transactions on a local Collection
79
80Local persistence reserves the utility names `acceptMutations`,
81`getLeadershipState`, and `forceReloadSubset`. If caller-supplied `utils`
82contains one of these properties, `persistedCollectionOptions` throws
83`InvalidPersistedCollectionConfigError` before it resolves persistence.
84This also applies to inherited properties and properties whose value is
85`undefined`. Other custom utility names remain available. Collections with a
86`sync` option retain their adapter utilities without this local-only restriction.
87
88For a Collection without a `sync` option, normal Collection mutations persist automatically. A manual transaction must call `acceptMutations` in its mutation function:
89
90```ts
91import { createTransaction } from '@tanstack/db'
92
93const manualTransaction = createTransaction({
94 autoCommit: false,
95 mutationFn: async ({ transaction }) => {
96 await todos.utils.acceptMutations(transaction)
97 },
98})
99
100manualTransaction.mutate(() => {
101 todos.insert({ id: '2', title: 'Call home', completed: false })
102})
103
104await manualTransaction.commit()
105```
106
107### Load rows after reopening the database
108
109Keep the database open while its Collections run. To simulate a page restart, clean up the Collection and close the database:
110
111```ts
112await todos.cleanup()
113await database.close?.()
114```
115
116Open the same OPFS database and create a Collection with the same `id` and `schemaVersion`. Load its rows before you read them:
117
118```ts
119const reopenedDatabase = await openBrowserWASQLiteOPFSDatabase({
120 databaseName: 'app.sqlite',
121})
122const reopenedPersistence = createBrowserWASQLitePersistence({
123 database: reopenedDatabase,
124})
125const reopenedTodos = createCollection(
126 persistedCollectionOptions<Todo, string>({
127 id: 'todos',
128 getKey: (todo) => todo.id,
129 persistence: reopenedPersistence,
130 schemaVersion: 1,
131 }),
132)
133
134await reopenedTodos.preload()
135console.log(reopenedTodos.get('1')?.title) // 'Buy milk'
136
137await reopenedTodos.cleanup()
138await reopenedDatabase.close?.()
139```
140
141## Temporal values
142
143SQLite persistence preserves `Temporal.Instant` and `Temporal.PlainDate` as
144native values, including nested fields, metadata and replay. Register the same
145Temporal implementation globally before writing or reopening persisted data.
146On a runtime without native Temporal, for example:
147
148```ts
149import 'temporal-polyfill/global'
150```
151
152Missing constructors and other Temporal kinds reject explicitly. Strings remain
153strings. Equality retains the Temporal kind and canonical text, including a
154PlainDate's calendar; ordering follows Temporal comparison. Supported native
155predicates and persisted expression indexes use the existing SQL filtering and
156in-memory cleanup pipeline without reducing nanosecond precision.
157
158This support applies to the shared SQLite adapter and local persisted wrapper.
159The remote-subset coordinator wire domain does not include Temporal literals;
160those requests reject before remote retry admission. If retained local demand
161becomes remote after an ownership change, fallback sequence-gap recovery fails
162the current Collection sync run before retrying that invalid request. This is a
163terminal Collection error: later active subsets are not recovered, subsequent
164loads reject with the same error, and later coordinator messages do not resume
165the failed run. Existing acquisitions can still be released. Multiprocess
166transport of native Temporal rows is not covered by this support claim.
167
168Values already stored as `{}` cannot be recovered. If an older version damaged
169a synced cache, replace it through the existing `schemaVersion` and schema-reset
170policy, then refetch. Updating the library does not automatically erase data.
171Also rebuild an older cache if ordinary objects used the reserved
172`__tanstack_db_persisted_type__` marker with a newly recognized type name. Older
173writes did not escape those objects, so their original meaning is ambiguous.
174New writes escape the marker and preserve the ordinary object.
175Older library versions cannot interpret the new Temporal encoding. Changed
176expression indexes rebuild when first ensured after upgrade. Later startups reuse
177those indexes. A changed native-literal or escaped-record signature can leave an
178obsolete registry entry and index until an explicit schema reset; this release
179does not reclaim those entries automatically. Increment the affected synced
180Collection's `schemaVersion` and retain its reset policy to rebuild that cache.
181The reset removes its old values and indexes before reading the new schema;
182other Collections with unchanged schema versions retain their caches. Refetch
183from the upstream source after reset.
184
185## Add persistence to a synced Collection
186
187Pass the options from a sync adapter into `persistedCollectionOptions`. The wrapper keeps that adapter's sync behavior and stores its applied data in SQLite.
188
189For example, you can wrap a Query Collection. This separate example uses the imports and `Todo` type from the browser example above:
190
191```ts
192import { QueryClient } from '@tanstack/query-core'
193import { queryCollectionOptions } from '@tanstack/query-db-collection'
194
195const syncedDatabase = await openBrowserWASQLiteOPFSDatabase({
196 databaseName: 'synced.sqlite',
197})
198const syncedPersistence = createBrowserWASQLitePersistence({
199 database: syncedDatabase,
200})
201const queryClient = new QueryClient()
202
203const syncedTodos = createCollection(
204 persistedCollectionOptions<Todo, string>({
205 ...queryCollectionOptions<Todo, string>({
206 id: 'synced-todos',
207 queryClient,
208 queryKey: ['todos'],
209 queryFn: async () => {
210 const response = await fetch('http://localhost:3000/api/todos')
211 if (!response.ok) throw new Error('Could not load todos')
212 return (await response.json()) as Array<Todo>
213 },
214 getKey: (todo) => todo.id,
215 }),
216 persistence: syncedPersistence,
217 schemaVersion: 1,
218 initialRender: {
219 strategy: 'network-first',
220 networkTimeoutMs: 3_000,
221 },
222 }),
223)
224```
225
226Install `@tanstack/query-core` and `@tanstack/query-db-collection` to use this example. Change the URL to your server. You can wrap another Collection sync adapter in the same way.
227
228The `initialRender` option is optional. It lets the Collection become ready from restored SQLite rows when the network is slow or unavailable. See [Render after SQLite restore](#render-after-sqlite-restore).
229
230Keep `syncedDatabase` open while `syncedTodos` runs. During normal shutdown, await `syncedTodos.cleanup()` and then `syncedDatabase.close?.()`.
231
232The `sync` option determines which mode the wrapper uses:
233
234| Collection options | SQLite behavior |
235| --- | --- |
236| `sync` present | Load persisted rows, then apply source sync transactions. The source remains responsible for current data. |
237| `sync` absent | Load and save local rows through a loopback sync adapter. The Collection has no remote source. |
238
239The wrapper also supports `syncMode: 'on-demand'`. In that mode, it loads rows for active query demand rather than loading every stored row into the Collection. When no query needs rows, a peer reload or schema reset checks rows already visible in the Collection but does not add unrelated stored rows.
240
241Built-in SQLite adapters use managed generations for on-demand caches. If a cache claim expires, the wrapper retires the old source callbacks, cleans up that source session, rotates the cache, and calls a custom source's `sync` function again. A custom source does not need a restart hook. Query and Electric provide `restartAfterScopedRecovery` to control their own restart; their hooks must retire old callbacks immediately and start replacement loads after `cacheRotated` resolves.
242
243An on-demand cache is not yet a certified offline snapshot. The first managed generation does not import legacy cache tables, and a private replacement created after claim expiry is not the next run's shared cache. A later launch must refetch those subsets from the source.
244
245## Render after SQLite restore
246
247Without `initialRender`, a persisted Collection becomes `ready` when its sync adapter calls `markReady()`, like any other Collection. The restored rows are in the Collection while it loads, but `status` stays `loading`.
248
249With `initialRender: { strategy: 'network-first', networkTimeoutMs }`, the Collection prefers the network for `networkTimeoutMs` (default 3 seconds). It becomes `ready` from the restored rows when both of these are true:
250
251- the SQLite restore completed and installed at least one row, and
252- the deadline passed, or the sync adapter failed its first load.
253
254The status is the only signal. Every hook, Suspense, and `preload()` follow it, so you do not need a separate persisted flag:
255
256```tsx
257import { useLiveQuery } from '@tanstack/react-db'
258
259function TodosView() {
260 const { data, isLoading, isLoadingError, isSyncError } = useLiveQuery((q) =>
261 q.from({ syncedTodos }),
262 )
263 if (isLoading) return <p>Loading todos...</p>
264 if (isLoadingError) return <p>Could not load todos.</p>
265 return (
266 <>
267 {isSyncError && <p>Showing saved todos. Sync is having trouble.</p>}
268 <ul>{data.map((todo: Todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
269 </>
270 )
271}
272```
273
274These rules keep `ready` meaningful:
275
276- **An empty restore waits for the network.** The Collection stays `loading` until the sync adapter answers, so an empty list always means "no rows". A Collection that last synced to zero rows also waits, because the restore cannot tell the two cases apart.
277- **The restore comes first.** If the sync adapter answers before the restore completes, the answer waits for the restore. A remote failure then opens the Collection from restored rows and shows the failure as a sync error (`isSyncError`, `collection.health.error`). Without restored rows, the first load fails (`status: 'error'`).
278- **A failed restore is a crash.** The Collection becomes `crashed`, because local storage cannot serve reads.
279- **The deadline does not stop network sync.** Network changes apply over the restored rows when they arrive.
280
281`initialRender` requires an eager persisted Collection. It does not support `syncMode: 'on-demand'`, which has no complete startup snapshot.
282
283Suspense uses the same status. This React component uses the `syncedTodos` Collection configured above:
284
285```tsx
286import { Suspense } from 'react'
287import { useLiveSuspenseQuery } from '@tanstack/react-db'
288
289function TodosList() {
290 const { data } = useLiveSuspenseQuery((q) => q.from({ syncedTodos }))
291 return <ul>{data.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
292}
293
294function TodosScreen() {
295 return (
296 <Suspense fallback={<p>Loading todos...</p>}>
297 <TodosList />
298 </Suspense>
299 )
300}
301```
302
303Place `TodosScreen` inside an [Error Boundary](./error-handling.md#using-suspense-and-error-boundaries-react) to handle a failed first load or a crash.
304
305Restored rows do not prove current authorization. Isolate SQLite data by user or tenant. If an authorization failure must hide cached rows, block the view separately: a remote failure can open the Collection from restored rows.
306
307## Browser tabs and Electron renderers
308
309The browser package uses single-tab coordination by default. If tabs share one OPFS database, give the persistence instance a `BrowserCollectionCoordinator`. It elects an owner for each Collection and routes writes between tabs. Replace the initial database and persistence setup with this code in each tab:
310
311```ts
312import { BrowserCollectionCoordinator } from '@tanstack/browser-db-sqlite-persistence'
313
314const database = await openBrowserWASQLiteOPFSDatabase({
315 databaseName: 'app.sqlite',
316})
317const coordinator = new BrowserCollectionCoordinator({ dbName: 'app' })
318const persistence = createBrowserWASQLitePersistence({
319 database,
320 coordinator,
321})
322```
323
324Pass this persistence instance to `persistedCollectionOptions`. During normal shutdown, clean up the Collections, dispose the coordinator, and close the database.
325
326The Electron package uses a main-process SQLite owner and a renderer bridge. Add `ElectronCollectionCoordinator` when multiple renderers share the database.
327
328These coordinators belong to SQLite persistence. The offline transaction executor has separate leader election for its outbox. Configure each system for the storage it owns.
329
330The browser database uses a worker. Its OPFS setup needs a secure context and browser support for OPFS. Close the database during normal shutdown. After a page returns from the back/forward cache, create fresh database and Collection instances.
331
332## Node.js alternative
333
334For a Node.js process, install `@tanstack/node-db-sqlite-persistence` and `better-sqlite3` in place of the browser packages. Open a file with `better-sqlite3` and pass it to the Node factory:
335
336```ts
337import Database from 'better-sqlite3'
338import {
339 createNodeSQLitePersistence,
340 persistedCollectionOptions,
341} from '@tanstack/node-db-sqlite-persistence'
342
343const nodeDatabase = new Database('./app.sqlite')
344const nodePersistence = createNodeSQLitePersistence({
345 database: nodeDatabase,
346})
347```
348
349Use `nodePersistence` in the Collection options shown above. Clean up each Collection before you call `nodeDatabase.close()`. The [Node package README](https://github.com/TanStack/db/tree/main/packages/node-db-sqlite-persistence#readme) has a complete example.
350
351## Schema versions and recovery
352
353By default, a synced Collection resets its persisted data after a schema mismatch. Its sync adapter must then load current data. A Collection without `sync` reports an error instead. It has no source that can restore deleted local rows.
354
355All runtime factories listed above except the Electron renderer factory accept `schemaMismatchPolicy`. An explicit `reset` policy can delete local data, so use it only when your application can restore that data.
356
357The Node package prunes its applied transaction log by default. Its [README](https://github.com/TanStack/db/tree/main/packages/node-db-sqlite-persistence#applied-transaction-pruning) lists the limits and options. If a resume position is older than the retained log, persistence loads a full snapshot.
358
359## Errors and limits
360
361An unavailable browser storage capability raises `PersistenceUnavailableError`. A durable write failure raises `PersistedCollectionDurabilityError` and crashes the Collection: it moves to `crashed` even after it was ready, and so does every live query and Effect over it. `reload()` rejects; recover with `cleanup({ dependents: true })` and `preload()` (see [When a Collection crashes](./error-handling.md#when-a-collection-crashes)).
362
363Failures from the wrapped sync adapter keep their usual meaning. Before the Collection is ready, the adapter's `fail` fails the first load (see [Render after SQLite restore](#render-after-sqlite-restore) for `initialRender`). After it, the adapter's `reportError`, `reportHealthy`, and `fail` appear in `collection.health` and in each live query's `health` tree, and the persisted rows stay. A failure of persistence itself crashes the Collection. In a follower tab, a failed request routed to the leader appears as a request error on the query that asked for the data.
364
365If a coordinated write loses its response, the result can be uncertain. `IndeterminateCommitError` means the application must check the durable state before it retries that write.
366
367Persistence retains source data and metadata. It does not define how an application sends local changes to a server. Use a mutation handler or the [offline transactions guide](./offline-transactions.md) for that work.