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

sqlite-persistence.md

315 lines15.0 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## Add persistence to a synced Collection
134​
135Pass the options from a sync adapter into `persistedCollectionOptions`. The wrapper keeps that adapter's sync behavior and stores its applied data in SQLite.
136​
137For example, you can wrap a Query Collection. This separate example uses the imports and `Todo` type from the browser example above:
138​
139```ts
140import { QueryClient } from '@tanstack/query-core'
141import { queryCollectionOptions } from '@tanstack/query-db-collection'
142​
143const syncedDatabase = await openBrowserWASQLiteOPFSDatabase({
144 databaseName: 'synced.sqlite',
145})
146const syncedPersistence = createBrowserWASQLitePersistence({
147 database: syncedDatabase,
148})
149const queryClient = new QueryClient()
150​
151const syncedTodos = createCollection(
152 persistedCollectionOptions<Todo, string>({
153 ...queryCollectionOptions<Todo, string>({
154 id: 'synced-todos',
155 queryClient,
156 queryKey: ['todos'],
157 queryFn: async () => {
158 const response = await fetch('http://localhost:3000/api/todos')
159 if (!response.ok) throw new Error('Could not load todos')
160 return (await response.json()) as Array<Todo>
161 },
162 getKey: (todo) => todo.id,
163 }),
164 persistence: syncedPersistence,
165 schemaVersion: 1,
166 initialRender: {
167 strategy: 'network-first',
168 networkTimeoutMs: 3_000,
169 },
170 }),
172```
173​
174Install `@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.
175​
176The `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.
177​
178Keep `syncedDatabase` open while `syncedTodos` runs. During normal shutdown, await `syncedTodos.cleanup()` and then `syncedDatabase.close?.()`.
179​
180The `sync` option determines which mode the wrapper uses:
181​
182| Collection options | SQLite behavior |
183| --- | --- |
184| `sync` present | Load persisted rows, then apply source sync transactions. The source remains responsible for current data. |
185| `sync` absent | Load and save local rows through a loopback sync adapter. The Collection has no remote source. |
186​
187The 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.
188​
189## Render after SQLite restore
190​
191`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.
192​
193Install the React binding to use the following components:
194​
195```sh
196npm install @tanstack/react-db
197```
198​
199A regular React live query exposes both readiness signals:
200​
201```tsx
202import { useLiveQuery } from '@tanstack/react-db'
203​
204function TodosView() {
205 const result = useLiveQuery((q) => q.from({ syncedTodos }))
206 const readiness = result.isReady
207 ? 'Collection ready'
208 : result.isPersistedReady
209 ? 'SQLite restore complete. Collection readiness pending'
210 : 'Waiting for Collection or SQLite restore'
211​
212 return (
213 <>
214 <p>{readiness}</p>
215 <ul>{result.data.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
216 </>
217 )
219```
220​
221`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.
222​
223The 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.
224​
225React, Solid, and Svelte read these values as properties. Angular reads signals such as `result.isPersistedReady()`. Vue reads refs such as `result.isPersistedReady.value`.
226​
227React and Solid Suspense can use the same option for network-first initial rendering. This React component uses the `syncedTodos` Collection configured above:
228​
229```tsx
230import { Suspense } from 'react'
231import { useLiveSuspenseQuery } from '@tanstack/react-db'
232​
233function TodosList() {
234 const { data } = useLiveSuspenseQuery((q) => q.from({ syncedTodos }))
235 return <ul>{data.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
237​
238function TodosScreen() {
239 return (
240 <Suspense fallback={<p>Loading todos...</p>}>
241 <TodosList />
242 </Suspense>
243 )
245```
246​
247Place `TodosScreen` inside an [Error Boundary](./error-handling.md#using-suspense-and-error-boundaries-react) to handle initial failures.
248​
249Suspense 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.
250​
251A 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.
252​
253A 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.
254​
255Persisted 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.
256​
257## Browser tabs and Electron renderers
258​
259The 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:
260​
261```ts
262import { BrowserCollectionCoordinator } from '@tanstack/browser-db-sqlite-persistence'
263​
264const database = await openBrowserWASQLiteOPFSDatabase({
265 databaseName: 'app.sqlite',
266})
267const coordinator = new BrowserCollectionCoordinator({ dbName: 'app' })
268const persistence = createBrowserWASQLitePersistence({
269 database,
270 coordinator,
271})
272```
273​
274Pass this persistence instance to `persistedCollectionOptions`. During normal shutdown, clean up the Collections, dispose the coordinator, and close the database.
275​
276The Electron package uses a main-process SQLite owner and a renderer bridge. Add `ElectronCollectionCoordinator` when multiple renderers share the database.
277​
278These coordinators belong to SQLite persistence. The offline transaction executor has separate leader election for its outbox. Configure each system for the storage it owns.
279​
280The 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.
281​
282## Node.js alternative
283​
284For 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:
285​
286```ts
287import Database from 'better-sqlite3'
288import {
289 createNodeSQLitePersistence,
290 persistedCollectionOptions,
291} from '@tanstack/node-db-sqlite-persistence'
292​
293const nodeDatabase = new Database('./app.sqlite')
294const nodePersistence = createNodeSQLitePersistence({
295 database: nodeDatabase,
296})
297```
298​
299Use `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.
300​
301## Schema versions and recovery
302​
303By 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.
304​
305All 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.
306​
307The 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.
308​
309## Errors and limits
310​
311An unavailable browser storage capability raises `PersistenceUnavailableError`. A durable write failure raises `PersistedCollectionDurabilityError` and puts the Collection in its error state.
312​
313If 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.
314​
315Persistence 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.