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

README.md

457 lines16.3 KB

1# @tanstack/offline-transactions
2​
3This package gives the leader a durable outbox for pending TanStack DB mutations. It retries stored mutations when the server is available. Read the [Offline Transactions guide](../../docs/guides/offline-transactions.md) for setup and lifecycle behavior.
4​
5## Features
6​
7- **Outbox**: The leader stores mutations before sending them when `isOfflineEnabled` is true
8- **Automatic Retry**: Configurable retry behavior with exponential backoff + jitter by default
9- **Multi-tab Coordination**: Leader election chooses one tab to process the outbox
10- **FIFO Sequential Processing**: Transactions execute one at a time in creation order
11- **Flexible Storage**: IndexedDB with localStorage fallback
12- **Type Safe**: Full TypeScript support with TanStack DB integration
13​
14## Installation
15​
16### Web
17​
18```bash
19npm install @tanstack/offline-transactions
20```
21​
22### React Native / Expo
23​
24```bash
25npm install @tanstack/offline-transactions @react-native-community/netinfo
26```
27​
28The React Native entry point uses `@react-native-community/netinfo` for connectivity detection. Supply a `StorageAdapter` for the outbox. The package does not include an AsyncStorage adapter.
29​
30## Platform Support
31​
32This package provides platform-specific implementations for web and React Native environments:
33​
34- **Web**: Uses browser APIs (`window.online` and `document.visibilitychange` events). Visible tabs let the executor process the outbox even when `navigator.onLine` is false; hidden tabs follow that hint. Errors from named mutation functions still use the retry decision and backoff. Visibility is local to each tab and does not transfer leadership from a hidden tab.
35- **React Native**: Uses React Native primitives (`@react-native-community/netinfo` for network status, `AppState` for foreground/background detection)
36​
37## Quick Start
38​
39Use the entry point for your platform. React Native also needs a storage adapter, as shown in the [guide](../../docs/guides/offline-transactions.md#react-native-and-expo).
40​
41**Web:**
42​
43```typescript
44import { startOfflineExecutor } from '@tanstack/offline-transactions'
45```
46​
47**React Native / Expo:**
48​
49```typescript
50import { startOfflineExecutor } from '@tanstack/offline-transactions/react-native'
51```
52​
53**Web usage:**
54​
55```typescript
56// Setup offline executor
57const offline = startOfflineExecutor({
58 collections: { todos: todoCollection },
59 mutationFns: {
60 syncTodos: async ({ transaction, idempotencyKey }) => {
61 await api.saveBatch(transaction.mutations, { idempotencyKey })
62 },
63 },
64 onLeadershipChange: (isLeader) => {
65 if (!isLeader) {
66 console.warn('Running in online-only mode (another tab is the leader)')
67 }
68 },
69})
70​
71await offline.waitForInit()
72​
73// Create offline transactions
74const offlineTx = offline.createOfflineTransaction({
75 mutationFnName: 'syncTodos',
76 autoCommit: false,
77})
78​
79const transaction = offlineTx.mutate(() => {
80 todoCollection.insert({
81 id: crypto.randomUUID(),
82 text: 'Buy milk',
83 completed: false,
84 })
85})
86​
87// Commit can remain pending while offline. Observe final failure.
88void offlineTx.commit().catch((error) => console.error(error))
89void transaction.isPersisted.promise.catch((error) => console.error(error))
90```
91​
92On React Native, pass a custom `storage` adapter to `startOfflineExecutor`.
93​
94## Core Concepts
95​
96### Durable Outbox
97​
98When `isOfflineEnabled` is true, the executor records a mutation before it sends the mutation to the server. The optimistic change appears before the outbox write settles:
99​
1001. The Collection applies an optimistic mutation.
1012. The leader writes the transaction to the outbox.
1023. When online, the executor calls the named mutation function.
1034. After a successful call, the executor attempts to remove the outbox entry.
104​
105An optimistic change does not prove that the outbox write succeeded. Handle transaction failures, and use an idempotency key on the server because an attempt can run more than once.
106​
107### Multi-tab Coordination
108​
109Only one tab acts as the "leader" to safely manage the outbox:
110​
111- **Leader tab**: Full offline support with outbox persistence
112- **Non-leader tabs**: Online-only mode for safety
113- **Leadership transfer**: Automatic failover when leader tab closes
114​
115### FIFO Sequential Processing
116​
117The executor processes one transaction at a time, in creation order:
118​
119- **Sequential execution**: All transactions execute in FIFO order
120- **Dependency safety**: Avoids conflicts between transactions that may reference each other
121- **Predictable behavior**: Transactions complete in creation order
122​
123## API Reference
124​
125### startOfflineExecutor(config)
126​
127Creates and starts an offline executor instance.
128​
129```typescript
130interface OfflineConfig {
131 collections: Record<string, Collection>
132 mutationFns: Record<string, MutationFn>
133 storage?: StorageAdapter
134 maxConcurrency?: number
135 jitter?: boolean
136 shouldRetry?: (error: Error, retryCount: number) => boolean | undefined
137 beforeRetry?: (transactions: OfflineTransaction[]) => OfflineTransaction[]
138 onUnknownMutationFn?: (name: string, tx: OfflineTransaction) => void
139 onLeadershipChange?: (isLeader: boolean) => void
140 onlineDetector?: OnlineDetector
142```
143​
144### Retry decisions
145​
146`shouldRetry` receives the named mutation function's `Error` and the current
147retry count, which is `0` on the first failure. The same `Error` instance is
148passed through; a rejection with a non-`Error` value is converted to an `Error`
149and may lose custom fields. Return `true` to retry, `false` to remove the
150offline transaction from the outbox and reject its
151waiting promises with that error, or `undefined` to use the default
152decision. The hook is synchronous and shared by all named mutation functions.
153An async hook returns a Promise, which fails its outbox row. Put any
154function-specific context needed by the hook on the thrown error. For example,
155this allows a 401 retry while keeping the default decision for other errors.
156The named mutation function must throw an error that retains the HTTP response
157status:
158​
159```typescript
160import {
161 NonRetriableError,
162 startOfflineExecutor,
163} from '@tanstack/offline-transactions'
164​
165class HttpError extends Error {
166 constructor(readonly status: number) {
167 super(`HTTP ${status}`)
168 this.name = 'HttpError'
169 }
171​
172const offline = startOfflineExecutor({
173 collections: { todos: todoCollection },
174 mutationFns: {
175 syncTodos: async ({ transaction, idempotencyKey }) => {
176 const response = await fetch('/api/todos', {
177 method: 'POST',
178 headers: {
179 'Content-Type': 'application/json',
180 'Idempotency-Key': idempotencyKey,
181 },
182 body: JSON.stringify(transaction.mutations),
183 })
184 // This todo API treats these responses as permanent. Classify other
185 // statuses according to the server contract.
186 if ([404, 405, 409, 410, 422].includes(response.status)) {
187 throw new NonRetriableError(`Todo request rejected: ${response.status}`)
188 }
189 if (!response.ok) throw new HttpError(response.status)
190 },
191 },
192 shouldRetry: (error) =>
193 error instanceof HttpError && error.status === 401 ? true : undefined,
194})
195```
196​
197A retried transaction retains its FIFO position, so use this when the
198authentication problem can recover. The app must refresh credentials separately
199before another attempt.
200​
201`NonRetriableError` always stops retry without calling the hook. The default
202policy still determines backoff and the `jitter` option. A hook that throws or
203returns another value records a terminal rejection for that row, removes it
204from the outbox, and rejects its waiting promises with the hook failure. Once
205the deletion is acknowledged, queued rows continue in creation order. New
206commits may join the queue during cleanup, but cannot run ahead of the failed
207row's deletion. The named mutation function error is logged; the hook failure
208is the caller-facing and stored error. A fresh executor does not replay the
209failed row. Stored errors retain `name`, `message`, and `stack`, but a restart
210does not restore an arbitrary error subclass or its custom fields.
211If terminal marker storage or deletion fails, the caller still rejects with
212the hook failure and the executor batch rejects with the storage error. The
213executor then stops with queued work retained. A marked row skips the named
214mutation function after restart; an unmarked row may replay.
215​
216### OfflineExecutor
217​
218#### Properties
219​
220- `isOfflineEnabled: boolean` - Whether this tab can persist offline transactions
221​
222#### Methods
223​
224- `createOfflineTransaction(options)` - Create a manual offline transaction
225- `waitForTransactionCompletion(id)` - Wait for a specific transaction to complete. Call it before the transaction settles: a waiter for a transaction that this executor recently settled (one of its last 1,000) rejects. A waiter for an older settled id keeps waiting. A waiter for an id the executor does not know yet keeps waiting, because another tab can still queue that transaction.
226- `removeFromOutbox(id)` - Manually remove transaction from outbox
227- `clearOutbox()` - Manually remove all outbox transactions
228- `peekOutbox()` - View all pending transactions
229- `dispose()` - Clean up resources
230​
231An acknowledged `removeFromOutbox(id)` or `clearOutbox()` while a named
232mutation function is running does not cancel that call. If the call later
233fails, its waiting promises reject with the named mutation function error; the
234removed row is not retried.
235​
236### Error Handling
237​
238Use `NonRetriableError` for permanent failures:
239​
240```typescript
241import { NonRetriableError } from '@tanstack/offline-transactions'
242​
243const mutationFn = async ({ transaction }) => {
244 try {
245 await api.save(transaction.mutations)
246 } catch (error) {
247 if (error.status === 422) {
248 throw new NonRetriableError('Invalid data - will not retry')
249 }
250 throw error // Will retry with backoff
251 }
253```
254​
255## Advanced Usage
256​
257### Custom Storage Adapter
258​
259```typescript
260import {
261 IndexedDBAdapter,
262 LocalStorageAdapter,
263} from '@tanstack/offline-transactions'
264​
265const executor = startOfflineExecutor({
266 // Use custom storage
267 storage: new IndexedDBAdapter('my-app', 'transactions'),
268 // ... other config
269})
270```
271​
272### Manual Transaction Control
273​
274```typescript
275const tx = executor.createOfflineTransaction({
276 mutationFnName: 'syncData',
277 autoCommit: false,
278})
279​
280tx.mutate(() => {
281 collection.insert({ id: '1', text: 'Item 1' })
282 collection.insert({ id: '2', text: 'Item 2' })
283})
284​
285// Commit when ready
286await tx.commit()
287```
288​
289## Tracking Submission Status
290​
291The `Transaction` returned by `mutate()` exposes local transaction state. Its
292`state` starts as `pending`, becomes `persisting` during commit, and settles as
293`completed` or `failed`. A rollback can move it to `failed` before or during
294persistence. `isPersisted.promise` settles at the same success or failure
295boundary.
296​
297On the offline-execution path, successful settlement means the configured
298`mutationFn` returned and the storage adapter acknowledged outbox deletion.
299It means the server confirmed or exposed the write only when that
300`mutationFn` explicitly waits for the provider's acknowledgement, read-back, or
301sync observation before returning.
302​
303After `mutationFn` returns, the executor records a `deletion-pending` outbox
304phase before removing the row. If recording that phase or removing the row
305fails, `commit()`, `isPersisted.promise`, and the per-ID completion waiter reject
306with the storage error. The executor stops: it does not retry the deletion,
307process queued peers, or admit new transactions. A fresh executor can remove a
308marked row without calling `mutationFn` again; `beforeRetry` only filters rows
309whose provider work is still pending. An unmarked row can replay after a crash
310or a failed phase write, so providers must honor the supplied `idempotencyKey`.
311Outbox removal means the storage adapter acknowledged deletion; it does not
312establish physical power-loss durability or exactly-once provider execution.
313If an app removes a row during an active provider call, that caller still waits
314for the provider call to return before it settles.
315​
316After a permanent provider failure, the caller rejects with that provider
317error. The executor records a `rejection-pending` outbox phase before removing
318the row. If the phase write or deletion fails, the executor batch throws the
319storage error and stops with queued peers untouched. A fresh executor skips
320provider work and optimistic restoration for a marked row. If writing the
321marker failed, the unmarked row may replay after restart.
322​
323```typescript
324const offlineTx = offline.createOfflineTransaction({
325 mutationFnName: 'syncTodos',
326 autoCommit: false,
327})
328​
329const tx = offlineTx.mutate(() => {
330 todoCollection.insert({ id: '1', text: 'Buy milk', completed: false })
331})
332​
333console.log(tx.state) // 'pending'
334​
335try {
336 await Promise.all([offlineTx.commit(), tx.isPersisted.promise])
337 console.log(tx.state) // 'completed'
338} catch (error) {
339 showSubmissionError(error)
341```
342​
343### Tracking Every Pending Transaction for an Item
344​
345An item can have more than one transaction in flight. Track transaction
346identities rather than storing one replaceable boolean or deleting an
347item-keyed entry unconditionally:
348​
349```typescript
350import type { Transaction } from '@tanstack/db'
351​
352const pendingByItem = new Map<string, Set<Transaction>>()
353​
354function trackPending(itemId: string, tx: Transaction) {
355 const pending = pendingByItem.get(itemId) ?? new Set<Transaction>()
356 pending.add(tx)
357 pendingByItem.set(itemId, pending)
358​
359 const removeThisTransaction = () => {
360 pending.delete(tx)
361 if (pending.size === 0 && pendingByItem.get(itemId) === pending) {
362 pendingByItem.delete(itemId)
363 }
364 }
365​
366 // Handle fulfillment and rejection so cleanup does not create another
367 // rejected Promise chain.
368 void tx.isPersisted.promise.then(removeThisTransaction, removeThisTransaction)
370​
371function isPending(itemId: string): boolean {
372 return (pendingByItem.get(itemId)?.size ?? 0) > 0
374```
375​
376Using only `pendingItems.delete(itemId)` in an older transaction's completion
377handler is unsafe because it can remove a newer transaction's status. A map that
378represents only "the latest submission" must compare the current entry with the finishing transaction before cleanup:
379​
380```typescript
381if (latestByItem.get(itemId) === tx) {
382 latestByItem.delete(itemId)
384```
385​
386That latest-only map can still be empty while an older transaction is pending
387if the newer transaction settles first. Use a set as above when the UI must
388answer whether _any_ submission remains pending.
389​
390### Inspecting Offline Work
391​
392The executor exposes point-in-time scheduler counts and the durable outbox:
393​
394```typescript
395// Scheduled entries. The pending count can include the currently running entry.
396const pendingCount = offline.getPendingCount()
397const runningCount = offline.getRunningCount()
398​
399// Durable entries, including retry metadata.
400const outbox = await offline.peekOutbox()
401for (const entry of outbox) {
402 console.log(entry.id, entry.retryCount, entry.lastError)
404```
405​
406These values describe local executor work, not backend confirmation. A normal
407retriable error leaves the transaction queued. A `NonRetriableError` marks a
408permanent failure, rejects the caller, and rolls back its optimistic state.
409The outbox entry remains until storage acknowledges its removal.
410​
411## Migration from TanStack DB
412​
413This package uses explicit offline transactions to provide offline capabilities:
414​
415```typescript
416// Before: Standard TanStack DB (online only)
417todoCollection.insert({ id: '1', text: 'Buy milk' })
418​
419// After: Explicit offline transactions
420const offline = startOfflineExecutor({
421 collections: { todos: todoCollection },
422 mutationFns: {
423 syncTodos: async ({ transaction }) => {
424 await api.sync(transaction.mutations)
425 },
426 },
427})
428​
429await offline.waitForInit()
430​
431const tx = offline.createOfflineTransaction({
432 mutationFnName: 'syncTodos',
433 autoCommit: false,
434})
435tx.mutate(() => todoCollection.insert({ id: '1', text: 'Buy milk' }))
436await tx.commit() // Waits for the mutation function and outbox deletion.
437```
438​
439## Platform Support
440​
441### Web Browsers
442​
443- **IndexedDB**: Modern browsers (primary storage)
444- **localStorage**: Fallback for limited environments
445- **Web Locks API**: Chrome 69+, Firefox 96+ (preferred leader election)
446- **BroadcastChannel**: All modern browsers (fallback leader election)
447​
448### React Native
449​
450- **React Native**: 0.70+ (package peer dependency)
451- **Expo**: Use the React Native entry point
452- **Required peer dependency**: `@react-native-community/netinfo` for network connectivity detection
453- **Storage**: Supply a custom `StorageAdapter`, such as the [example AsyncStorage adapter](../../examples/react-native/offline-transactions/src/db/AsyncStorageAdapter.ts)
454​
455## License
456​
457MIT