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

README.md

378 lines12.5 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 allow sync attempts even when `navigator.onLine` is false; hidden tabs follow that hint. Request failures still use the configured retry policy. 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 beforeRetry?: (transactions: OfflineTransaction[]) => OfflineTransaction[]
137 onUnknownMutationFn?: (name: string, tx: OfflineTransaction) => void
138 onLeadershipChange?: (isLeader: boolean) => void
139 onlineDetector?: OnlineDetector
141```
142​
143### OfflineExecutor
144​
145#### Properties
146​
147- `isOfflineEnabled: boolean` - Whether this tab can persist offline transactions
148​
149#### Methods
150​
151- `createOfflineTransaction(options)` - Create a manual offline transaction
152- `waitForTransactionCompletion(id)` - Wait for a specific transaction to complete
153- `removeFromOutbox(id)` - Manually remove transaction from outbox
154- `peekOutbox()` - View all pending transactions
155- `dispose()` - Clean up resources
156​
157### Error Handling
158​
159Use `NonRetriableError` for permanent failures:
160​
161```typescript
162import { NonRetriableError } from '@tanstack/offline-transactions'
163​
164const mutationFn = async ({ transaction }) => {
165 try {
166 await api.save(transaction.mutations)
167 } catch (error) {
168 if (error.status === 422) {
169 throw new NonRetriableError('Invalid data - will not retry')
170 }
171 throw error // Will retry with backoff
172 }
174```
175​
176## Advanced Usage
177​
178### Custom Storage Adapter
179​
180```typescript
181import {
182 IndexedDBAdapter,
183 LocalStorageAdapter,
184} from '@tanstack/offline-transactions'
185​
186const executor = startOfflineExecutor({
187 // Use custom storage
188 storage: new IndexedDBAdapter('my-app', 'transactions'),
189 // ... other config
190})
191```
192​
193### Manual Transaction Control
194​
195```typescript
196const tx = executor.createOfflineTransaction({
197 mutationFnName: 'syncData',
198 autoCommit: false,
199})
200​
201tx.mutate(() => {
202 collection.insert({ id: '1', text: 'Item 1' })
203 collection.insert({ id: '2', text: 'Item 2' })
204})
205​
206// Commit when ready
207await tx.commit()
208```
209​
210## Tracking Submission Status
211​
212The `Transaction` returned by `mutate()` exposes local transaction state. Its
213`state` starts as `pending`, becomes `persisting` during commit, and settles as
214`completed` or `failed`. A rollback can move it to `failed` before or during
215persistence. `isPersisted.promise` settles at the same success or failure
216boundary.
217​
218On the offline-execution path, successful settlement means the configured
219`mutationFn` returned and the storage adapter acknowledged outbox deletion.
220It means the server confirmed or exposed the write only when that
221`mutationFn` explicitly waits for the provider's acknowledgement, read-back, or
222sync observation before returning.
223​
224After `mutationFn` returns, the executor records a `deletion-pending` outbox
225phase before removing the row. If recording that phase or removing the row
226fails, `commit()`, `isPersisted.promise`, and the per-ID completion waiter reject
227with the storage error. The executor stops: it does not retry the deletion,
228process queued peers, or admit new transactions. A fresh executor can remove a
229marked row without calling `mutationFn` again; `beforeRetry` only filters rows
230whose provider work is still pending. An unmarked row can replay after a crash
231or a failed phase write, so providers must honor the supplied `idempotencyKey`.
232Outbox removal means the storage adapter acknowledged deletion; it does not
233establish physical power-loss durability or exactly-once provider execution.
234If an app removes a row during an active provider call, that caller still waits
235for the provider call to return before it settles.
236​
237After a permanent provider failure, the caller rejects with that provider
238error. The executor records a `rejection-pending` outbox phase before removing
239the row. If the phase write or deletion fails, the executor batch throws the
240storage error and stops with queued peers untouched. A fresh executor skips
241provider work and optimistic restoration for a marked row. If writing the
242marker failed, the unmarked row may replay after restart.
243​
244```typescript
245const offlineTx = offline.createOfflineTransaction({
246 mutationFnName: 'syncTodos',
247 autoCommit: false,
248})
249​
250const tx = offlineTx.mutate(() => {
251 todoCollection.insert({ id: '1', text: 'Buy milk', completed: false })
252})
253​
254console.log(tx.state) // 'pending'
255​
256try {
257 await Promise.all([offlineTx.commit(), tx.isPersisted.promise])
258 console.log(tx.state) // 'completed'
259} catch (error) {
260 showSubmissionError(error)
262```
263​
264### Tracking Every Pending Transaction for an Item
265​
266An item can have more than one transaction in flight. Track transaction
267identities rather than storing one replaceable boolean or deleting an
268item-keyed entry unconditionally:
269​
270```typescript
271import type { Transaction } from '@tanstack/db'
272​
273const pendingByItem = new Map<string, Set<Transaction>>()
274​
275function trackPending(itemId: string, tx: Transaction) {
276 const pending = pendingByItem.get(itemId) ?? new Set<Transaction>()
277 pending.add(tx)
278 pendingByItem.set(itemId, pending)
279​
280 const removeThisTransaction = () => {
281 pending.delete(tx)
282 if (pending.size === 0 && pendingByItem.get(itemId) === pending) {
283 pendingByItem.delete(itemId)
284 }
285 }
286​
287 // Handle fulfillment and rejection so cleanup does not create another
288 // rejected Promise chain.
289 void tx.isPersisted.promise.then(removeThisTransaction, removeThisTransaction)
291​
292function isPending(itemId: string): boolean {
293 return (pendingByItem.get(itemId)?.size ?? 0) > 0
295```
296​
297Using only `pendingItems.delete(itemId)` in an older transaction's completion
298handler is unsafe because it can remove a newer transaction's status. A map that
299represents only "the latest submission" must compare the current entry with the finishing transaction before cleanup:
300​
301```typescript
302if (latestByItem.get(itemId) === tx) {
303 latestByItem.delete(itemId)
305```
306​
307That latest-only map can still be empty while an older transaction is pending
308if the newer transaction settles first. Use a set as above when the UI must
309answer whether _any_ submission remains pending.
310​
311### Inspecting Offline Work
312​
313The executor exposes point-in-time scheduler counts and the durable outbox:
314​
315```typescript
316// Scheduled entries. The pending count can include the currently running entry.
317const pendingCount = offline.getPendingCount()
318const runningCount = offline.getRunningCount()
319​
320// Durable entries, including retry metadata.
321const outbox = await offline.peekOutbox()
322for (const entry of outbox) {
323 console.log(entry.id, entry.retryCount, entry.lastError)
325```
326​
327These values describe local executor work, not backend confirmation. A normal
328retriable error leaves the transaction queued. A `NonRetriableError` marks a
329permanent failure, rejects the caller, and rolls back its optimistic state.
330The outbox entry remains until storage acknowledges its removal.
331​
332## Migration from TanStack DB
333​
334This package uses explicit offline transactions to provide offline capabilities:
335​
336```typescript
337// Before: Standard TanStack DB (online only)
338todoCollection.insert({ id: '1', text: 'Buy milk' })
339​
340// After: Explicit offline transactions
341const offline = startOfflineExecutor({
342 collections: { todos: todoCollection },
343 mutationFns: {
344 syncTodos: async ({ transaction }) => {
345 await api.sync(transaction.mutations)
346 },
347 },
348})
349​
350await offline.waitForInit()
351​
352const tx = offline.createOfflineTransaction({
353 mutationFnName: 'syncTodos',
354 autoCommit: false,
355})
356tx.mutate(() => todoCollection.insert({ id: '1', text: 'Buy milk' }))
357await tx.commit() // Waits for the mutation function and outbox deletion.
358```
359​
360## Platform Support
361​
362### Web Browsers
363​
364- **IndexedDB**: Modern browsers (primary storage)
365- **localStorage**: Fallback for limited environments
366- **Web Locks API**: Chrome 69+, Firefox 96+ (preferred leader election)
367- **BroadcastChannel**: All modern browsers (fallback leader election)
368​
369### React Native
370​
371- **React Native**: 0.70+ (package peer dependency)
372- **Expo**: Use the React Native entry point
373- **Required peer dependency**: `@react-native-community/netinfo` for network connectivity detection
374- **Storage**: Supply a custom `StorageAdapter`, such as the [example AsyncStorage adapter](../../examples/react-native/offline-transactions/src/db/AsyncStorageAdapter.ts)
375​
376## License
377​
378MIT