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

sqlite-persistence.md

363 lines18.4 KB

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
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 }),
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​
80For a Collection without a `sync` option, normal Collection mutations persist automatically. A manual transaction must call `acceptMutations` in its mutation function:
81​
82```ts
83import { createTransaction } from '@tanstack/db'
84​
85const manualTransaction = createTransaction({
86 autoCommit: false,
87 mutationFn: async ({ transaction }) => {
88 await todos.utils.acceptMutations(transaction)
89 },
90})
91​
92manualTransaction.mutate(() => {
93 todos.insert({ id: '2', title: 'Call home', completed: false })
94})
95​
96await manualTransaction.commit()
97```
98​
99### Load rows after reopening the database
100​
101Keep the database open while its Collections run. To simulate a page restart, clean up the Collection and close the database:
102​
103```ts
104await todos.cleanup()
105await database.close?.()
106```
107​
108Open the same OPFS database and create a Collection with the same `id` and `schemaVersion`. Load its rows before you read them:
109​
110```ts
111const reopenedDatabase = await openBrowserWASQLiteOPFSDatabase({
112 databaseName: 'app.sqlite',
113})
114const reopenedPersistence = createBrowserWASQLitePersistence({
115 database: reopenedDatabase,
116})
117const reopenedTodos = createCollection(
118 persistedCollectionOptions<Todo, string>({
119 id: 'todos',
120 getKey: (todo) => todo.id,
121 persistence: reopenedPersistence,
122 schemaVersion: 1,
123 }),
125​
126await reopenedTodos.preload()
127console.log(reopenedTodos.get('1')?.title) // 'Buy milk'
128​
129await reopenedTodos.cleanup()
130await reopenedDatabase.close?.()
131```
132​
133## Temporal values
134​
135SQLite persistence preserves `Temporal.Instant` and `Temporal.PlainDate` as
136native values, including nested fields, metadata and replay. Register the same
137Temporal implementation globally before writing or reopening persisted data.
138On a runtime without native Temporal, for example:
139​
140```ts
141import 'temporal-polyfill/global'
142```
143​
144Missing constructors and other Temporal kinds reject explicitly. Strings remain
145strings. Equality retains the Temporal kind and canonical text, including a
146PlainDate's calendar; ordering follows Temporal comparison. Supported native
147predicates and persisted expression indexes use the existing SQL filtering and
148in-memory cleanup pipeline without reducing nanosecond precision.
149​
150This support applies to the shared SQLite adapter and local persisted wrapper.
151The remote-subset coordinator wire domain does not include Temporal literals;
152those requests reject before remote retry admission. If retained local demand
153becomes remote after an ownership change, fallback sequence-gap recovery fails
154the current Collection sync run before retrying that invalid request. This is a
155terminal Collection error: later active subsets are not recovered, subsequent
156loads reject with the same error, and later coordinator messages do not resume
157the failed run. Existing acquisitions can still be released. Multiprocess
158transport of native Temporal rows is not covered by this support claim.
159​
160Values already stored as `{}` cannot be recovered. If an older version damaged
161a synced cache, replace it through the existing `schemaVersion` and schema-reset
162policy, then refetch. Updating the library does not automatically erase data.
163Also rebuild an older cache if ordinary objects used the reserved
164`__tanstack_db_persisted_type__` marker with a newly recognized type name. Older
165writes did not escape those objects, so their original meaning is ambiguous.
166New writes escape the marker and preserve the ordinary object.
167Older library versions cannot interpret the new Temporal encoding. Changed
168expression indexes rebuild when first ensured after upgrade. Later startups reuse
169those indexes. A changed native-literal or escaped-record signature can leave an
170obsolete registry entry and index until an explicit schema reset; this release
171does not reclaim those entries automatically. Increment the affected synced
172Collection's `schemaVersion` and retain its reset policy to rebuild that cache.
173The reset removes its old values and indexes before reading the new schema;
174other Collections with unchanged schema versions retain their caches. Refetch
175from the upstream source after reset.
176​
177## Add persistence to a synced Collection
178​
179Pass the options from a sync adapter into `persistedCollectionOptions`. The wrapper keeps that adapter's sync behavior and stores its applied data in SQLite.
180​
181For example, you can wrap a Query Collection. This separate example uses the imports and `Todo` type from the browser example above:
182​
183```ts
184import { QueryClient } from '@tanstack/query-core'
185import { queryCollectionOptions } from '@tanstack/query-db-collection'
186​
187const syncedDatabase = await openBrowserWASQLiteOPFSDatabase({
188 databaseName: 'synced.sqlite',
189})
190const syncedPersistence = createBrowserWASQLitePersistence({
191 database: syncedDatabase,
192})
193const queryClient = new QueryClient()
194​
195const syncedTodos = createCollection(
196 persistedCollectionOptions<Todo, string>({
197 ...queryCollectionOptions<Todo, string>({
198 id: 'synced-todos',
199 queryClient,
200 queryKey: ['todos'],
201 queryFn: async () => {
202 const response = await fetch('http://localhost:3000/api/todos')
203 if (!response.ok) throw new Error('Could not load todos')
204 return (await response.json()) as Array<Todo>
205 },
206 getKey: (todo) => todo.id,
207 }),
208 persistence: syncedPersistence,
209 schemaVersion: 1,
210 initialRender: {
211 strategy: 'network-first',
212 networkTimeoutMs: 3_000,
213 },
214 }),
216```
217​
218Install `@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.
219​
220The `initialRender` option is optional. It lets live queries report when SQLite restore completes. It also lets React and Solid Suspense use restored rows for the first render while the Collection is not ready.
221​
222Keep `syncedDatabase` open while `syncedTodos` runs. During normal shutdown, await `syncedTodos.cleanup()` and then `syncedDatabase.close?.()`.
223​
224The `sync` option determines which mode the wrapper uses:
225​
226| Collection options | SQLite behavior |
227| --- | --- |
228| `sync` present | Load persisted rows, then apply source sync transactions. The source remains responsible for current data. |
229| `sync` absent | Load and save local rows through a loopback sync adapter. The Collection has no remote source. |
230​
231The 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.
232​
233Built-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.
234​
235An 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.
236​
237## Render after SQLite restore
238​
239`initialRender` requires an eager persisted Collection. It does not support `syncMode: 'on-demand'`, which has no complete startup snapshot. Set it on every source Collection in a live query. If one source does not opt in, the query cannot report persisted readiness or use the restored snapshot as its initial-render fallback.
240​
241Install the React binding to use the following components:
242​
243```sh
244npm install @tanstack/react-db
245```
246​
247A regular React live query exposes both readiness signals:
248​
249```tsx
250import { useLiveQuery } from '@tanstack/react-db'
251​
252function TodosView() {
253 const result = useLiveQuery((q) => q.from({ syncedTodos }))
254 const readiness = result.isReady
255 ? 'Collection ready'
256 : result.isPersistedReady
257 ? 'SQLite restore complete. Collection readiness pending'
258 : 'Waiting for Collection or SQLite restore'
259​
260 return (
261 <>
262 <p>{readiness}</p>
263 <ul>{result.data.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
264 </>
265 )
267```
268​
269`isReady` reports Collection readiness. `isPersistedReady` reports that every opted-in source finished its current eager restore, even when SQLite had no rows. These flags do not identify where each visible row came from. A regular `useLiveQuery` does not wait for the network-first deadline before it renders rows.
270​
271The hooks also expose `persistedStatus` and `persistedError`. The status is `unavailable` if a source did not opt in, `loading` during restore, `ready` after every restore completes, or `error` if a restore fails. `persistedError` keeps the restore error. An SSR seed does not count as a SQLite restore.
272​
273React, Solid, and Svelte read these values as properties. Angular reads signals such as `result.isPersistedReady()`. Vue reads refs such as `result.isPersistedReady.value`.
274​
275React and Solid Suspense can use the same option for network-first initial rendering. This React component uses the `syncedTodos` Collection configured above:
276​
277```tsx
278import { Suspense } from 'react'
279import { useLiveSuspenseQuery } from '@tanstack/react-db'
280​
281function TodosList() {
282 const { data } = useLiveSuspenseQuery((q) => q.from({ syncedTodos }))
283 return <ul>{data.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
285​
286function TodosScreen() {
287 return (
288 <Suspense fallback={<p>Loading todos...</p>}>
289 <TodosList />
290 </Suspense>
291 )
293```
294​
295Place `TodosScreen` inside an [Error Boundary](./error-handling.md#using-suspense-and-error-boundaries-react) to handle initial failures.
296​
297Suspense prefers Collection readiness. If it remains pending after `networkTimeoutMs`, a completed SQLite restore can release the first render. The default is 3 seconds. Set `networkTimeoutMs: 0` to allow fallback as soon as restore completes. For a query with multiple sources, the longest configured deadline applies. The deadline does not stop network sync.
298​
299A source failure can allow fallback before the deadline. React also waits for restore if its client query stream fails before the first render, including before the component mounts. Once every restore succeeds, React renders the derived query result, even if it is empty.
300​
301A derived-query failure still reaches the surrounding React Error Boundary. If the network-first wait rejects, its error reaches that boundary. A successful network load can render even if restore failed or a source did not opt in.
302​
303Persisted readiness does not prove current authorization. Isolate SQLite data by user or tenant. If an authorization failure must hide cached rows, block the view separately. The fallback does not classify source errors.
304​
305## Browser tabs and Electron renderers
306​
307The 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:
308​
309```ts
310import { BrowserCollectionCoordinator } from '@tanstack/browser-db-sqlite-persistence'
311​
312const database = await openBrowserWASQLiteOPFSDatabase({
313 databaseName: 'app.sqlite',
314})
315const coordinator = new BrowserCollectionCoordinator({ dbName: 'app' })
316const persistence = createBrowserWASQLitePersistence({
317 database,
318 coordinator,
319})
320```
321​
322Pass this persistence instance to `persistedCollectionOptions`. During normal shutdown, clean up the Collections, dispose the coordinator, and close the database.
323​
324The Electron package uses a main-process SQLite owner and a renderer bridge. Add `ElectronCollectionCoordinator` when multiple renderers share the database.
325​
326These coordinators belong to SQLite persistence. The offline transaction executor has separate leader election for its outbox. Configure each system for the storage it owns.
327​
328The 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.
329​
330## Node.js alternative
331​
332For 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:
333​
334```ts
335import Database from 'better-sqlite3'
336import {
337 createNodeSQLitePersistence,
338 persistedCollectionOptions,
339} from '@tanstack/node-db-sqlite-persistence'
340​
341const nodeDatabase = new Database('./app.sqlite')
342const nodePersistence = createNodeSQLitePersistence({
343 database: nodeDatabase,
344})
345```
346​
347Use `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.
348​
349## Schema versions and recovery
350​
351By 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.
352​
353All 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.
354​
355The 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.
356​
357## Errors and limits
358​
359An unavailable browser storage capability raises `PersistenceUnavailableError`. A durable write failure raises `PersistedCollectionDurabilityError` and puts the Collection in its error state.
360​
361If 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.
362​
363Persistence 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.