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
32class HttpError extends Error {
33 constructor(readonly status: number) {
34 super(`HTTP ${status}`)
35 this.name = 'HttpError'
36 }
37}
38
39const executor = startOfflineExecutor({
40 collections: { todos },
41 mutationFns: {
42 saveTodo: async ({ transaction, idempotencyKey }) => {
43 const todo = transaction.mutations[0]?.modified as Todo | undefined
44 if (!todo) throw new NonRetriableError('Todo mutation is missing')
45
46 const response = await fetch('/api/todos', {
47 method: 'POST',
48 headers: {
49 'Content-Type': 'application/json',
50 'Idempotency-Key': idempotencyKey,
51 },
52 body: JSON.stringify(todo),
53 })
54
55 if (response.status === 422) {
56 throw new NonRetriableError('The server rejected this todo')
57 }
58 // This todo API treats these responses as permanent.
59 if ([404, 405, 409, 410].includes(response.status)) {
60 throw new NonRetriableError(`Todo request rejected: ${response.status}`)
61 }
62 if (!response.ok) throw new HttpError(response.status)
63
64 // Wait for a server read or sync observation here if your app needs it.
65 },
66 },
67})
68
69await executor.waitForInit()
70
71const addTodo = executor.createOfflineAction<Todo>({
72 mutationFnName: 'saveTodo',
73 onMutate: (todo) => {
74 todos.insert(todo)
75 },
76})
77
78const transaction = addTodo({
79 id: crypto.randomUUID(),
80 title: 'Buy milk',
81 completed: false,
82})
83
84// Report final failure. This promise can stay pending offline.
85void transaction.when('settled').catch((error) => console.error(error))
86```
87
88`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.
89
90When `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.
91The todo examples assume 404, 405, 409, 410, and 422 are permanent for their
92server. Change that classification to match your server contract. Responses
93such as 408 and 429 can be recoverable.
94
95Set `shouldRetry(error, retryCount)` on the executor config to change the
96retry decision after a named mutation function rejects. Return `true` to retry,
97`false` to stop, or `undefined` to keep the default decision. For example, the
98hook can return `true` for a recoverable 401 and `undefined` for other errors:
99
100```ts
101shouldRetry: (error) =>
102 error instanceof HttpError && error.status === 401 ? true : undefined,
103```
104
105`fetch` does not reject on an HTTP error response. The named mutation function
106above throws an `HttpError` that carries the numeric status. Retry a 401 only
107when the app can refresh its credentials between attempts.
108The hook receives the named mutation function's `Error` and a retry count of
109`0` on the first failure. The same `Error` instance is passed through; a
110rejection with a non-`Error` value is converted to an `Error` and may lose
111custom fields.
112The hook is synchronous and shared by all named mutation functions. An async
113hook returns a Promise, which fails its outbox row. Put function-specific
114context on the thrown error when retry rules differ between functions.
115`NonRetriableError` always stops without calling the hook. Retry delays and
116configured jitter remain unchanged. A retried offline transaction keeps its
117FIFO position. If the hook throws or returns another value, the executor
118records a terminal rejection, removes only that outbox row, and rejects its
119`when('settled')` promise with the hook failure. Once deletion is acknowledged,
120queued transactions continue in creation order. New commits may join the queue
121during cleanup, but cannot run ahead of the failed row's deletion. A fresh
122executor does not replay the failed row. The named mutation function error is
123logged; the hook failure is the caller-facing and stored error. Stored errors
124retain `name`, `message`, and `stack`, but a restart does not restore an
125arbitrary error subclass or its custom fields. If writing the terminal marker or
126deleting the row fails, the caller still rejects with the hook failure while
127the executor stops with the storage error and retains queued work. A saved
128marker prevents a provider call on restart; an unmarked row can replay.
129
130If an outbox phase write or deletion fails after `mutationFn` settles, the
131executor stops processing queued work, and its batch promise rejects with the
132storage error. The affected transaction's `when('settled')` promise also rejects
133with the storage error after a successful mutation function, with the named
134mutation function error after a terminal provider failure, or with the hook
135error after a retry decision failure. After storage recovers,
136restart the offline executor over the retained outbox. A durable phase marker
137prevents another named mutation function call. If the marker write failed,
138that function may be called again.
139
140The 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.
141
142## Wait for the right result
143
144`waitForInit()` waits for storage setup, leader election, and the initial outbox read. It does not wait for every pending mutation to reach the server.
145
146`transaction.when('settled')` settles when the offline transaction completes
147or fails. Successful settlement means the configured `mutationFn` returned and
148the storage adapter acknowledged outbox deletion. It proves server confirmation
149only if that function waits for a server acknowledgement, read-back, or sync
150observation. If deletion fails, the promise rejects with the storage error.
151A server must honor the supplied idempotency key because a crash before
152the executor records provider completion can replay the request.
153
154Do not await `transaction.when('settled')` 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.
155
156For a multi-step manual transaction, use `createOfflineTransaction`:
157
158```ts
159const offlineTransaction = executor.createOfflineTransaction({
160 mutationFnName: 'saveBatch',
161 autoCommit: false,
162})
163
164offlineTransaction.mutate(() => {
165 todos.insert({ id: crypto.randomUUID(), title: 'First', completed: false })
166 todos.insert({ id: crypto.randomUUID(), title: 'Second', completed: false })
167})
168
169void offlineTransaction.commit().catch((error) => console.error(error))
170```
171
172Register `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.
173
174## Storage and leadership
175
176On 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.
177
178One 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.
179
180If neither election API exists, the current fallback treats the tab as the leader. It does not coordinate multiple tabs.
181
182Check `mode`, `storageDiagnostic`, and `isOfflineEnabled` after `waitForInit()`. `mode` describes storage availability. `isOfflineEnabled` also requires leadership.
183
184```ts
185await executor.waitForInit()
186
187console.log(executor.mode)
188console.log(executor.storageDiagnostic)
189console.log(executor.isOfflineEnabled)
190```
191
192Use `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.
193
194## React Native and Expo
195
196Install 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:
197
198```sh
199npm install @tanstack/offline-transactions @react-native-community/netinfo @react-native-async-storage/async-storage
200```
201
202```ts
203import { startOfflineExecutor } from '@tanstack/offline-transactions/react-native'
204import { AsyncStorageAdapter } from './AsyncStorageAdapter'
205
206const executor = startOfflineExecutor({
207 collections: { todos },
208 storage: new AsyncStorageAdapter('offline-todos:'),
209 mutationFns: { saveTodo },
210})
211
212await executor.waitForInit()
213```
214
215The `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`.
216
217The executor does not probe a custom storage adapter. If the initial outbox read fails, `waitForInit()` rejects. Handle that error during app startup.
218
219The React Native entry point uses `ReactNativeOnlineDetector` by default. It uses NetInfo and app state events. Pass `onlineDetector` if your app needs another connectivity rule.
220
221## Inspect and manage pending work
222
223```ts
224const entries = await executor.peekOutbox()
225const pending = executor.getPendingCount()
226const running = executor.getRunningCount()
227```
228
229The 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.
230
231`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.
232
233The executor also exposes `removeFromOutbox(id)` and `clearOutbox()`. Use these
234only when the application decides to discard pending writes. An acknowledged
235removal does not cancel a running named mutation function. If that call later
236fails, its waiting promises reject with the named mutation function error and
237the removed row is not retried. Call `dispose()` when the executor's owner ends.
238
239## Use SQLite persistence with the outbox
240
241This 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:
242
243```sh
244npm install @tanstack/db @tanstack/query-core @tanstack/query-db-collection \
245 @tanstack/react-native-db-sqlite-persistence @op-engineering/op-sqlite \
246 @tanstack/offline-transactions @react-native-async-storage/async-storage \
247 @react-native-community/netinfo
248```
249
250Copy 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.
251
252Keep 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.
253
254```ts
255import { open } from '@op-engineering/op-sqlite'
256import { QueryClient } from '@tanstack/query-core'
257import { createCollection } from '@tanstack/db'
258import {
259 NonRetriableError,
260 startOfflineExecutor,
261} from '@tanstack/offline-transactions/react-native'
262import { queryCollectionOptions } from '@tanstack/query-db-collection'
263import {
264 createReactNativeSQLitePersistence,
265 persistedCollectionOptions,
266} from '@tanstack/react-native-db-sqlite-persistence'
267import { AsyncStorageAdapter } from './AsyncStorageAdapter'
268
269type Todo = { id: string; title: string; completed: boolean }
270const apiUrl = 'https://api.example.com/todos' // Replace with your server URL.
271
272class HttpError extends Error {
273 constructor(readonly status: number) {
274 super(`HTTP ${status}`)
275 this.name = 'HttpError'
276 }
277}
278
279const database = open({ name: 'todos.sqlite', location: 'default' })
280const persistence = createReactNativeSQLitePersistence({ database })
281const queryClient = new QueryClient()
282
283const todos = createCollection(
284 persistedCollectionOptions<Todo, string>({
285 ...queryCollectionOptions<Todo, string>({
286 id: 'todos',
287 queryClient,
288 queryKey: ['todos'],
289 queryFn: async () => {
290 const response = await fetch(apiUrl)
291 if (!response.ok) throw new Error('Could not load todos')
292 return (await response.json()) as Array<Todo>
293 },
294 getKey: (todo) => todo.id,
295 }),
296 persistence,
297 schemaVersion: 1,
298 }),
299)
300
301const executor = startOfflineExecutor({
302 collections: { todos },
303 storage: new AsyncStorageAdapter('offline-todos:'),
304 mutationFns: {
305 saveTodo: async ({ transaction, idempotencyKey }) => {
306 const todo = transaction.mutations[0]?.modified as Todo | undefined
307 if (!todo) throw new NonRetriableError('Todo mutation is missing')
308
309 const response = await fetch(apiUrl, {
310 method: 'POST',
311 headers: {
312 'Content-Type': 'application/json',
313 'Idempotency-Key': idempotencyKey,
314 },
315 body: JSON.stringify(todo),
316 })
317
318 if (response.status === 422) {
319 throw new NonRetriableError('The server rejected this todo')
320 }
321 // This todo API treats these responses as permanent.
322 if ([404, 405, 409, 410].includes(response.status)) {
323 throw new NonRetriableError(`Todo request rejected: ${response.status}`)
324 }
325 if (!response.ok) throw new HttpError(response.status)
326 await todos.utils.refetch()
327 },
328 },
329})
330
331await executor.waitForInit()
332void todos.preload().catch((error) => console.error(error))
333
334const addTodo = executor.createOfflineAction<Todo>({
335 mutationFnName: 'saveTodo',
336 onMutate: (todo) => {
337 todos.insert(todo)
338 },
339})
340
341const transaction = addTodo({
342 id: crypto.randomUUID(),
343 title: 'Buy milk',
344 completed: false,
345})
346void transaction.when('settled').catch((error) => console.error(error))
347```
348
349For 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.
350
351The 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.health` (or the `health` tree of a live query over it) to report or retry the read.
352
353The [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.
354
355The [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.
356
357## Mutation value codecs
358
359The default outbox format preserves its existing JSON, Date, and Temporal behavior. For other mutation value domains, set `mutationCodec` to a codec with a stable `id`, synchronous `encode(value): string`, and synchronous `decode(encoded): unknown`.
360
361Encoded transactions use wire version 4 and retain the codec ID. Configure the same codec on restart. Missing or mismatched codecs, and decoder failures, reject the outbox read with the transaction ID while keeping its storage entry. Readers without version 4 support cannot replay these records. Default writers still emit version 3. A configured codec can read older records through their original decoder.
362
363The codec applies to `modified`, `original`, and `changes`. Transaction metadata keeps the default encoding. Codec functions must not perform network calls. TanStack's Convex adapter supplies `convexMutationCodec` for Convex values and removed fields.