Open History to see the last commit
1# @tanstack/offline-transactions
2
3Offline-first transaction capabilities for TanStack DB that provides durable persistence of mutations with automatic retry when connectivity is restored.
4
5## Features
6
7- **Outbox Pattern**: Persist mutations before dispatch for zero data loss
8- **Automatic Retry**: Configurable retry behavior with exponential backoff + jitter by default
9- **Multi-tab Coordination**: Leader election ensures safe storage access
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 implementation requires the `@react-native-community/netinfo` peer dependency for network connectivity detection.
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/offline` events, `document.visibilitychange`)
35- **React Native**: Uses React Native primitives (`@react-native-community/netinfo` for network status, `AppState` for foreground/background detection)
36
37## Quick Start
38
39Using offline transactions on web and React Native/Expo is identical except for the import. Choose the appropriate import based on your target platform:
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**Usage (same for both platforms):**
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
71// Create offline transactions
72const offlineTx = offline.createOfflineTransaction({
73 mutationFnName: 'syncTodos',
74 autoCommit: false,
75})
76
77offlineTx.mutate(() => {
78 todoCollection.insert({
79 id: crypto.randomUUID(),
80 text: 'Buy milk',
81 completed: false,
82 })
83})
84
85// Execute with automatic offline support
86await offlineTx.commit()
87```
88
89## Core Concepts
90
91### Outbox-First Persistence
92
93Mutations are persisted to a durable outbox before being applied, ensuring zero data loss during offline periods:
94
951. Mutation is persisted to IndexedDB/localStorage
962. Optimistic update is applied locally
973. When online, mutation is sent to server
984. On success, mutation is removed from outbox
99
100### Multi-tab Coordination
101
102Only one tab acts as the "leader" to safely manage the outbox:
103
104- **Leader tab**: Full offline support with outbox persistence
105- **Non-leader tabs**: Online-only mode for safety
106- **Leadership transfer**: Automatic failover when leader tab closes
107
108### FIFO Sequential Processing
109
110Transactions are processed one at a time in the order they were created:
111
112- **Sequential execution**: All transactions execute in FIFO order
113- **Dependency safety**: Avoids conflicts between transactions that may reference each other
114- **Predictable behavior**: Transactions complete in the exact order they were created
115
116## API Reference
117
118### startOfflineExecutor(config)
119
120Creates and starts an offline executor instance.
121
122```typescript
123interface OfflineConfig {
124 collections: Record<string, Collection>
125 mutationFns: Record<string, MutationFn>
126 storage?: StorageAdapter
127 maxConcurrency?: number
128 jitter?: boolean
129 beforeRetry?: (transactions: OfflineTransaction[]) => OfflineTransaction[]
130 onUnknownMutationFn?: (name: string, tx: OfflineTransaction) => void
131 onLeadershipChange?: (isLeader: boolean) => void
132 onlineDetector?: OnlineDetector
133}
134```
135
136### OfflineExecutor
137
138#### Properties
139
140- `isOfflineEnabled: boolean` - Whether this tab can persist offline transactions
141
142#### Methods
143
144- `createOfflineTransaction(options)` - Create a manual offline transaction
145- `waitForTransactionCompletion(id)` - Wait for a specific transaction to complete
146- `removeFromOutbox(id)` - Manually remove transaction from outbox
147- `peekOutbox()` - View all pending transactions
148- `dispose()` - Clean up resources
149
150### Error Handling
151
152Use `NonRetriableError` for permanent failures:
153
154```typescript
155import { NonRetriableError } from '@tanstack/offline-transactions'
156
157const mutationFn = async ({ transaction }) => {
158 try {
159 await api.save(transaction.mutations)
160 } catch (error) {
161 if (error.status === 422) {
162 throw new NonRetriableError('Invalid data - will not retry')
163 }
164 throw error // Will retry with backoff
165 }
166}
167```
168
169## Advanced Usage
170
171### Custom Storage Adapter
172
173```typescript
174import {
175 IndexedDBAdapter,
176 LocalStorageAdapter,
177} from '@tanstack/offline-transactions'
178
179const executor = startOfflineExecutor({
180 // Use custom storage
181 storage: new IndexedDBAdapter('my-app', 'transactions'),
182 // ... other config
183})
184```
185
186### Manual Transaction Control
187
188```typescript
189const tx = executor.createOfflineTransaction({
190 mutationFnName: 'syncData',
191 autoCommit: false,
192})
193
194tx.mutate(() => {
195 collection.insert({ id: '1', text: 'Item 1' })
196 collection.insert({ id: '2', text: 'Item 2' })
197})
198
199// Commit when ready
200await tx.commit()
201```
202
203## Tracking Submission Status
204
205The `Transaction` returned by `mutate()` exposes local transaction state. Its
206`state` starts as `pending`, becomes `persisting` during commit, and settles as
207`completed` or `failed`. A rollback can move it to `failed` before or during
208persistence. `isPersisted.promise` settles at the same success or failure
209boundary.
210
211On the offline-execution path, successful settlement means the configured
212`mutationFn` returned and the executor removed the transaction from its durable
213outbox. It means the server confirmed or exposed the write only when that
214`mutationFn` explicitly waits for the provider's acknowledgement, read-back, or
215sync observation before returning.
216
217```typescript
218const offlineTx = offline.createOfflineTransaction({
219 mutationFnName: 'syncTodos',
220 autoCommit: false,
221})
222
223const tx = offlineTx.mutate(() => {
224 todoCollection.insert({ id: '1', text: 'Buy milk', completed: false })
225})
226
227console.log(tx.state) // 'pending'
228
229try {
230 await Promise.all([offlineTx.commit(), tx.isPersisted.promise])
231 console.log(tx.state) // 'completed'
232} catch (error) {
233 showSubmissionError(error)
234}
235```
236
237### Tracking Every Pending Transaction for an Item
238
239An item can have more than one transaction in flight. Track transaction
240identities rather than storing one replaceable boolean or deleting an
241item-keyed entry unconditionally:
242
243```typescript
244import type { Transaction } from '@tanstack/db'
245
246const pendingByItem = new Map<string, Set<Transaction>>()
247
248function trackPending(itemId: string, tx: Transaction) {
249 const pending = pendingByItem.get(itemId) ?? new Set<Transaction>()
250 pending.add(tx)
251 pendingByItem.set(itemId, pending)
252
253 const removeThisTransaction = () => {
254 pending.delete(tx)
255 if (pending.size === 0 && pendingByItem.get(itemId) === pending) {
256 pendingByItem.delete(itemId)
257 }
258 }
259
260 // Handle fulfillment and rejection so cleanup does not create another
261 // rejected Promise chain.
262 void tx.isPersisted.promise.then(removeThisTransaction, removeThisTransaction)
263}
264
265function isPending(itemId: string): boolean {
266 return (pendingByItem.get(itemId)?.size ?? 0) > 0
267}
268```
269
270Using only `pendingItems.delete(itemId)` in an older transaction's completion
271handler is unsafe because it can erase a newer transaction's status. A map that
272represents only "the latest submission" must identity-check its cleanup:
273
274```typescript
275if (latestByItem.get(itemId) === tx) {
276 latestByItem.delete(itemId)
277}
278```
279
280That latest-only map can still be empty while an older transaction is pending
281if the newer transaction settles first. Use a set as above when the UI must
282answer whether _any_ submission remains pending.
283
284### Inspecting Offline Work
285
286The executor exposes point-in-time scheduler counts and the durable outbox:
287
288```typescript
289// Scheduled entries. The pending count can include the currently running entry.
290const pendingCount = offline.getPendingCount()
291const runningCount = offline.getRunningCount()
292
293// Durable entries, including retry metadata.
294const outbox = await offline.peekOutbox()
295for (const entry of outbox) {
296 console.log(entry.id, entry.retryCount, entry.lastError)
297}
298```
299
300These values describe local executor work, not backend confirmation. A normal
301retriable error leaves the transaction queued. A `NonRetriableError` marks a
302permanent failure, removes the outbox entry, and rolls back its optimistic
303state.
304
305## Migration from TanStack DB
306
307This package uses explicit offline transactions to provide offline capabilities:
308
309```typescript
310// Before: Standard TanStack DB (online only)
311todoCollection.insert({ id: '1', text: 'Buy milk' })
312
313// After: Explicit offline transactions
314const offline = startOfflineExecutor({
315 collections: { todos: todoCollection },
316 mutationFns: {
317 syncTodos: async ({ transaction }) => {
318 await api.sync(transaction.mutations)
319 },
320 },
321})
322
323const tx = offline.createOfflineTransaction({ mutationFnName: 'syncTodos' })
324tx.mutate(() => todoCollection.insert({ id: '1', text: 'Buy milk' }))
325await tx.commit() // Works offline!
326```
327
328## Platform Support
329
330### Web Browsers
331
332- **IndexedDB**: Modern browsers (primary storage)
333- **localStorage**: Fallback for limited environments
334- **Web Locks API**: Chrome 69+, Firefox 96+ (preferred leader election)
335- **BroadcastChannel**: All modern browsers (fallback leader election)
336
337### React Native
338
339- **React Native**: 0.60+ (tested with latest versions)
340- **Expo**: SDK 40+ (tested with latest versions)
341- **Required peer dependency**: `@react-native-community/netinfo` for network connectivity detection
342- **Storage**: Uses AsyncStorage or custom storage adapters
343
344## License
345
346MIT