Open History to see the last commit
1---
2title: Offline Transactions
3id: offline-transactions
4---
5
6`@tanstack/offline-transactions` gives the leader a durable outbox for pending mutations. The executor retries stored mutations when it can reach the server. The leader restores their optimistic state after a restart.
7
8The outbox stores pending writes. [SQLite persistence](./sqlite-persistence.md) stores Collection rows. It can also save sync metadata for supported adapters. You can use either package alone or use them together.
9
10## Start on the web
11
12Install the package:
13
14```sh
15npm install @tanstack/offline-transactions
16```
17
18This example starts from an existing `todos` Collection. The server must accept the same idempotency key on repeated requests.
19
20Keep the `collections` registry keys and Collection IDs stable across restarts. The executor uses that registry to restore stored mutations.
21
22An action chooses its path when invoked. If `executor.isOfflineEnabled` is false then, it uses the online-only path without durable retry. If it selects the offline path but loses leadership before its outbox write, the transaction rejects with `NonRetriableError` and rolls back its optimistic change.
23
24```ts
25import {
26 NonRetriableError,
27 startOfflineExecutor,
28} from '@tanstack/offline-transactions'
29
30type Todo = { id: string; title: string; completed: boolean }
31
32const executor = startOfflineExecutor({
33 collections: { todos },
34 mutationFns: {
35 saveTodo: async ({ transaction, idempotencyKey }) => {
36 const todo = transaction.mutations[0]?.modified as Todo | undefined
37 if (!todo) throw new NonRetriableError('Todo mutation is missing')
38
39 const response = await fetch('/api/todos', {
40 method: 'POST',
41 headers: {
42 'Content-Type': 'application/json',
43 'Idempotency-Key': idempotencyKey,
44 },
45 body: JSON.stringify(todo),
46 })
47
48 if (response.status === 422) {
49 throw new NonRetriableError('The server rejected this todo')
50 }
51 if (!response.ok) throw new Error('Could not save the todo')
52
53 // Wait for a server read or sync observation here if your app needs it.
54 },
55 },
56})
57
58await executor.waitForInit()
59
60const addTodo = executor.createOfflineAction<Todo>({
61 mutationFnName: 'saveTodo',
62 onMutate: (todo) => {
63 todos.insert(todo)
64 },
65})
66
67const transaction = addTodo({
68 id: crypto.randomUUID(),
69 title: 'Buy milk',
70 completed: false,
71})
72
73// Report final failure. This promise can stay pending offline.
74void transaction.isPersisted.promise.catch((error) => console.error(error))
75```
76
77`onMutate` must be synchronous. It applies the optimistic change before the executor writes the outbox entry. If that write fails, the transaction fails. A visible optimistic change alone does not prove durable storage.
78
79When `isOfflineEnabled` is true, the executor calls the named `mutationFn` after it records the transaction. A temporary error leaves the entry available for retry. `NonRetriableError` marks a permanent failure and rolls back optimistic state.
80
81If an outbox phase write or deletion fails after `mutationFn` returns, the
82affected transaction rejects with the storage error and the executor stops
83processing queued work. If `mutationFn` failed permanently, its caller keeps
84that provider error while the executor batch reports the storage error. Restart
85with a fresh executor after storage recovers. A durable phase marker prevents
86another provider call; if the marker write failed, the provider may be called
87again.
88
89The executor sends a stable `idempotencyKey` with each attempt. A server can receive an attempt more than once, especially after a restart or leadership change. Make the server treat repeated keys as one logical mutation.
90
91## Wait for the right result
92
93`waitForInit()` waits for storage setup, leader election, and the initial outbox read. It does not wait for every pending mutation to reach the server.
94
95`transaction.isPersisted.promise` settles when the offline transaction completes
96or fails. Successful settlement means the configured `mutationFn` returned and
97the storage adapter acknowledged outbox deletion. It proves server confirmation
98only if that function waits for a server acknowledgement, read-back, or sync
99observation. If deletion fails, the promise rejects with the storage error.
100A server must honor the supplied idempotency key because a crash before
101the executor records provider completion can replay the request.
102
103Do not await `isPersisted.promise` before you show an offline page. A pending mutation can keep that promise open until connectivity returns. Use it to update submission status or report a final error.
104
105For a multi-step manual transaction, use `createOfflineTransaction`:
106
107```ts
108const offlineTransaction = executor.createOfflineTransaction({
109 mutationFnName: 'saveBatch',
110 autoCommit: false,
111})
112
113offlineTransaction.mutate(() => {
114 todos.insert({ id: crypto.randomUUID(), title: 'First', completed: false })
115 todos.insert({ id: crypto.randomUUID(), title: 'Second', completed: false })
116})
117
118void offlineTransaction.commit().catch((error) => console.error(error))
119```
120
121Register `saveBatch` in `mutationFns` before you use this example. `commit()` can remain pending during an offline period. The executor also offers `createOfflineAction` for one synchronous optimistic action.
122
123## Storage and leadership
124
125On the web, the executor tests IndexedDB first. It uses localStorage if IndexedDB is unavailable. You can pass a `storage` adapter to choose a different store.
126
127One tab leads outbox processing. The executor prefers Web Locks and then BroadcastChannel for leader election. A follower uses the normal online mutation path without an outbox entry. The same online-only path applies when durable storage is unavailable.
128
129If neither election API exists, the current fallback treats the tab as the leader. It does not coordinate multiple tabs.
130
131Check `mode`, `storageDiagnostic`, and `isOfflineEnabled` after `waitForInit()`. `mode` describes storage availability. `isOfflineEnabled` also requires leadership.
132
133```ts
134await executor.waitForInit()
135
136console.log(executor.mode)
137console.log(executor.storageDiagnostic)
138console.log(executor.isOfflineEnabled)
139```
140
141Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves.
142
143## React Native and Expo
144
145Install the package, its network detector, and storage for the example adapter. Copy the [AsyncStorageAdapter example](https://github.com/TanStack/db/blob/main/examples/react-native/offline-transactions/src/db/AsyncStorageAdapter.ts) into your app before you import it:
146
147```sh
148npm install @tanstack/offline-transactions @react-native-community/netinfo @react-native-async-storage/async-storage
149```
150
151```ts
152import { startOfflineExecutor } from '@tanstack/offline-transactions/react-native'
153import { AsyncStorageAdapter } from './AsyncStorageAdapter'
154
155const executor = startOfflineExecutor({
156 collections: { todos },
157 storage: new AsyncStorageAdapter('offline-todos:'),
158 mutationFns: { saveTodo },
159})
160
161await executor.waitForInit()
162```
163
164The `saveTodo` function and `todos` Collection use the same roles as the web example. `AsyncStorageAdapter` is an application adapter. The package does not export it. A custom adapter must implement `get`, `set`, `delete`, `keys`, and `clear` from `StorageAdapter`.
165
166The executor does not probe a custom storage adapter. If the initial outbox read fails, `waitForInit()` rejects. Handle that error during app startup.
167
168The React Native entry point uses `ReactNativeOnlineDetector` by default. It uses NetInfo and app state events. Pass `onlineDetector` if your app needs another connectivity rule.
169
170## Inspect and manage pending work
171
172```ts
173const entries = await executor.peekOutbox()
174const pending = executor.getPendingCount()
175const running = executor.getRunningCount()
176```
177
178The counts describe local work. An outbox entry can include a retry count, next attempt time, and last error. None of these values proves that the server applied the mutation.
179
180`beforeRetry` can remove entries during replay. `onUnknownMutationFn` reports an entry whose registered function is missing. Keep mutation function names stable across releases, or define a migration for stored entries.
181
182The executor also exposes `removeFromOutbox(id)` and `clearOutbox()`. Use these only when the application decides to discard pending writes. Call `dispose()` when the executor's owner ends.
183
184## Use SQLite persistence with the outbox
185
186This React Native recipe stores applied Collection rows in OP-SQLite and pending mutations in AsyncStorage. The Query Collection supplies server sync. Install the packages for both stores and for Query Collection sync:
187
188```sh
189npm install @tanstack/db @tanstack/query-core @tanstack/query-db-collection \
190 @tanstack/react-native-db-sqlite-persistence @op-engineering/op-sqlite \
191 @tanstack/offline-transactions @react-native-async-storage/async-storage \
192 @react-native-community/netinfo
193```
194
195Copy the [AsyncStorage adapter](https://github.com/TanStack/db/blob/main/examples/react-native/offline-transactions/src/db/AsyncStorageAdapter.ts) into your app. It implements `StorageAdapter`. Neither package exports this adapter. Use an absolute server URL that your device can reach.
196
197Keep the SQLite file name, Collection ID, `todos` registry key, `saveTodo` name, and outbox prefix stable across restarts. The server must treat repeated `Idempotency-Key` values as one mutation. The executor can retry a request after the server applies it.
198
199```ts
200import { open } from '@op-engineering/op-sqlite'
201import { QueryClient } from '@tanstack/query-core'
202import { createCollection } from '@tanstack/db'
203import {
204 NonRetriableError,
205 startOfflineExecutor,
206} from '@tanstack/offline-transactions/react-native'
207import { queryCollectionOptions } from '@tanstack/query-db-collection'
208import {
209 createReactNativeSQLitePersistence,
210 persistedCollectionOptions,
211} from '@tanstack/react-native-db-sqlite-persistence'
212import { AsyncStorageAdapter } from './AsyncStorageAdapter'
213
214type Todo = { id: string; title: string; completed: boolean }
215const apiUrl = 'https://api.example.com/todos' // Replace with your server URL.
216
217const database = open({ name: 'todos.sqlite', location: 'default' })
218const persistence = createReactNativeSQLitePersistence({ database })
219const queryClient = new QueryClient()
220
221const todos = createCollection(
222 persistedCollectionOptions<Todo, string>({
223 ...queryCollectionOptions<Todo, string>({
224 id: 'todos',
225 queryClient,
226 queryKey: ['todos'],
227 queryFn: async () => {
228 const response = await fetch(apiUrl)
229 if (!response.ok) throw new Error('Could not load todos')
230 return (await response.json()) as Array<Todo>
231 },
232 getKey: (todo) => todo.id,
233 }),
234 persistence,
235 schemaVersion: 1,
236 }),
237)
238
239const executor = startOfflineExecutor({
240 collections: { todos },
241 storage: new AsyncStorageAdapter('offline-todos:'),
242 mutationFns: {
243 saveTodo: async ({ transaction, idempotencyKey }) => {
244 const todo = transaction.mutations[0]?.modified as Todo | undefined
245 if (!todo) throw new NonRetriableError('Todo mutation is missing')
246
247 const response = await fetch(apiUrl, {
248 method: 'POST',
249 headers: {
250 'Content-Type': 'application/json',
251 'Idempotency-Key': idempotencyKey,
252 },
253 body: JSON.stringify(todo),
254 })
255
256 if (response.status === 422) {
257 throw new NonRetriableError('The server rejected this todo')
258 }
259 if (!response.ok) throw new Error('Could not save the todo')
260 await todos.utils.refetch()
261 },
262 },
263})
264
265await executor.waitForInit()
266void todos.preload().catch((error) => console.error(error))
267
268const addTodo = executor.createOfflineAction<Todo>({
269 mutationFnName: 'saveTodo',
270 onMutate: (todo) => {
271 todos.insert(todo)
272 },
273})
274
275const transaction = addTodo({
276 id: crypto.randomUUID(),
277 title: 'Buy milk',
278 completed: false,
279})
280void transaction.isPersisted.promise.catch((error) => console.error(error))
281```
282
283For the leader, `waitForInit()` waits for the initial outbox read and optimistic restoration attempt. It does not make `todos` ready. The separate `preload()` call starts Collection loading without blocking offline actions. A screen that needs initial rows can await `todos.preload()` and handle a rejection.
284
285The final `refetch()` asks the server for current rows after a successful write. By default, it can resolve when that read fails. The offline transaction can then settle successfully because the POST succeeded. That read error does not itself request an outbox retry. Check `todos.utils.isError` and `todos.utils.lastError` to report or retry the read.
286
287The [React Native offline transactions example](https://github.com/TanStack/db/tree/main/examples/react-native/offline-transactions) shows the full app structure. Its API client does not yet send an idempotency key, so use the request pattern above when you adapt it. The [shopping list example](https://github.com/TanStack/db/tree/main/examples/react-native/shopping-list) also shows Electric sync.
288
289The [Electron example](https://github.com/TanStack/db/tree/main/examples/electron/offline-first) uses a custom SQLite-backed `StorageAdapter` for the outbox. That adapter is separate from the persisted Collection tables.