Open History to see the last commit
1---
2title: Creating a Collection Options Creator
3id: guide/collection-options-creator
4---
5# Creating a Collection Options Creator
6
7A collection options creator is a factory function that generates configuration options for TanStack DB collections. It provides a standardized way to integrate different sync engines and data sources with TanStack DB's reactive sync-first architecture.
8
9## Overview
10
11Collection options creators follow a consistent pattern:
121. Accept configuration specific to the sync engine
132. Return an object that satisfies the `CollectionConfig` interface
143. Handle sync initialization, data parsing, and transaction management
154. Optionally provide utility functions specific to the sync engine
16
17## When to Create a Custom Collection
18
19You should create a custom collection when:
20- You have a dedicated sync engine (like ElectricSQL, Trailbase, Firebase, or a custom WebSocket solution)
21- You need specific sync behaviors that aren't covered by the query collection
22- You want to integrate with a backend that has its own sync protocol
23
24**Note**: If you're just hitting an API and returning data, use the query collection instead.
25
26## Core Requirements
27
28Every collection options creator must implement these key responsibilities:
29
30### 1. Configuration Interface
31
32Define a configuration interface that extends or includes standard collection properties:
33
34```typescript
35// Pattern A: User provides handlers (Query / ElectricSQL style)
36interface MyCollectionConfig<TItem extends object> {
37 // Your sync engine specific options
38 connectionUrl: string
39 apiKey?: string
41 // Standard collection properties
42 id?: string
43 schema?: StandardSchemaV1
44 getKey: (item: TItem) => string | number
45 sync?: SyncConfig<TItem>
47 rowUpdateMode?: 'partial' | 'full'
49 // User provides mutation handlers
50 onInsert?: InsertMutationFn<TItem>
51 onUpdate?: UpdateMutationFn<TItem>
52 onDelete?: DeleteMutationFn<TItem>
53}
54
55// Pattern B: Built-in handlers (Trailbase style)
56interface MyCollectionConfig<TItem extends object>
57 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
58 // Your sync engine specific options
59 recordApi: MyRecordApi<TItem>
60 connectionUrl: string
62 rowUpdateMode?: 'partial' | 'full'
64 // Note: onInsert/onUpdate/onDelete are implemented by your collection creator
65}
66```
67
68### 2. Sync Implementation
69
70The sync function is the heart of your collection. It must:
71
72The sync function must return a cleanup function for proper garbage collection:
73
74```typescript
75const sync: SyncConfig<T>['sync'] = (params) => {
76 const { begin, write, commit, markReady, collection } = params
78 // 1. Initialize connection to your sync engine
79 const connection = initializeConnection(config)
81 // 2. Set up real-time subscription FIRST (prevents race conditions)
82 const eventBuffer: Array<any> = []
83 let isInitialSyncComplete = false
85 connection.subscribe((event) => {
86 if (!isInitialSyncComplete) {
87 // Buffer events during initial sync to prevent race conditions
88 eventBuffer.push(event)
89 return
90 }
92 // Process real-time events
93 begin()
95 switch (event.type) {
96 case 'insert':
97 write({ type: 'insert', value: event.data })
98 break
99 case 'update':
100 write({ type: 'update', value: event.data })
101 break
102 case 'delete':
103 write({ type: 'delete', value: event.data })
104 break
105 }
107 commit()
108 })
110 // 3. Perform initial data fetch
111 async function initialSync() {
112 try {
113 const data = await fetchInitialData()
115 begin() // Start a transaction
117 for (const item of data) {
118 write({
119 type: 'insert',
120 value: item
121 })
122 }
124 commit() // Commit the transaction
126 // 4. Process buffered events
127 isInitialSyncComplete = true
128 if (eventBuffer.length > 0) {
129 begin()
130 for (const event of eventBuffer) {
131 // Deduplicate if necessary based on your sync engine
132 write({ type: event.type, value: event.data })
133 }
134 commit()
135 eventBuffer.splice(0)
136 }
138 } catch (error) {
139 console.error('Initial sync failed:', error)
140 throw error
141 } finally {
142 // ALWAYS call markReady, even on error
143 markReady()
144 }
145 }
146
147 initialSync()
149 // 4. Return cleanup function
150 return () => {
151 connection.close()
152 // Clean up any timers, intervals, or other resources
153 }
154}
155```
156
157### 3. Transaction Lifecycle
158
159Understanding the transaction lifecycle is important for correct implementation.
160
161The sync process follows this lifecycle:
162
1631. **begin()** - Start collecting changes
1642. **write()** - Add changes to the pending transaction (buffered until commit)
1653. **commit()** - Apply all changes atomically to the collection state
1664. **markReady()** - Signal that initial sync is complete
167
168**Race Condition Prevention:**
169Many sync engines start real-time subscriptions before the initial sync completes. Your implementation MUST deduplicate events that arrive via subscription that represent the same data as the initial sync. Consider:
170- Starting the listener BEFORE initial fetch and buffering events
171- Tracking timestamps, sequence numbers, or document versions
172- Using read timestamps or other ordering mechanisms
173
174### 4. Data Parsing and Type Conversion
175
176If your sync engine returns data with different types, provide conversion functions for specific fields:
177
178```typescript
179interface MyCollectionConfig<TItem, TRecord> {
180 // ... other config
182 // Only specify conversions for fields that need type conversion
183 parse: {
184 created_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
185 updated_at: (ts: number) => new Date(ts * 1000), // timestamp -> Date
186 metadata?: (str: string) => JSON.parse(str) // JSON string -> object
187 }
189 serialize: {
190 created_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
191 updated_at: (date: Date) => Math.floor(date.valueOf() / 1000), // Date -> timestamp
192 metadata?: (obj: object) => JSON.stringify(obj) // object -> JSON string
193 }
194}
195```
196
197**Type Conversion Examples:**
198```typescript
199// Firebase Timestamp to Date
200parse: {
201 createdAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
202 updatedAt: (timestamp) => timestamp?.toDate?.() || new Date(timestamp),
203}
204
205// PostGIS geometry to GeoJSON
206parse: {
207 location: (wkb: string) => parseWKBToGeoJSON(wkb)
208}
209
210// JSON string to object with error handling
211parse: {
212 metadata: (str: string) => {
213 try {
214 return JSON.parse(str)
215 } catch {
216 return {}
217 }
218 }
219}
220```
221
222### 5. Mutation Handler Patterns
223
224There are two distinct patterns for handling mutations in collection options creators:
225
226#### Pattern A: User-Provided Handlers (ElectricSQL, Query)
227
228The user provides mutation handlers in the config. Your collection creator passes them through:
229
230```typescript
231interface MyCollectionConfig<TItem extends object> {
232 // ... other config
234 // User provides these handlers
235 onInsert?: InsertMutationFn<TItem>
236 onUpdate?: UpdateMutationFn<TItem>
237 onDelete?: DeleteMutationFn<TItem>
238}
239
240export function myCollectionOptions<TItem extends object>(
241 config: MyCollectionConfig<TItem>
242) {
243 return {
244 // ... other options
245 rowUpdateMode: config.rowUpdateMode || 'partial',
247 // Pass through user-provided handlers (possibly with additional logic)
248 onInsert: config.onInsert ? async (params) => {
249 const result = await config.onInsert!(params)
250 // Additional sync coordination logic
251 return result
252 } : undefined
253 }
254}
255```
256
257#### Pattern B: Built-in Handlers (Trailbase, WebSocket, Firebase)
258
259Your collection creator implements the handlers directly using the sync engine's APIs:
260
261```typescript
262interface MyCollectionConfig<TItem extends object>
263 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete'> {
264 // ... sync engine specific config
265 // Note: onInsert/onUpdate/onDelete are NOT in the config
266}
267
268export function myCollectionOptions<TItem extends object>(
269 config: MyCollectionConfig<TItem>
270) {
271 return {
272 // ... other options
273 rowUpdateMode: config.rowUpdateMode || 'partial',
275 // Implement handlers using sync engine APIs
276 onInsert: async ({ transaction }) => {
277 // Handle provider-specific batch limits (e.g., Firestore's 500 limit)
278 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
280 for (const chunk of chunks) {
281 const ids = await config.recordApi.createBulk(
282 chunk.map(m => serialize(m.modified))
283 )
284 await awaitIds(ids)
285 }
287 return transaction.mutations.map(m => m.key)
288 },
290 onUpdate: async ({ transaction }) => {
291 const chunks = chunkArray(transaction.mutations, PROVIDER_BATCH_LIMIT)
293 for (const chunk of chunks) {
294 await Promise.all(
295 chunk.map(m =>
296 config.recordApi.update(m.key, serialize(m.changes))
297 )
298 )
299 }
301 await awaitIds(transaction.mutations.map(m => String(m.key)))
302 }
303 }
304}
305```
306
307Many providers have batch size limits (Firestore: 500, DynamoDB: 25, etc.) so chunk large transactions accordingly.
308
309Choose Pattern A when users need to provide their own APIs, and Pattern B when your sync engine handles writes directly.
310
311## Row Update Modes
312
313Collections support two update modes:
314
315- **`partial`** (default) - Updates are merged with existing data
316- **`full`** - Updates replace the entire row
317
318Configure this in your sync config:
319
320```typescript
321sync: {
322 sync: syncFn,
323 rowUpdateMode: 'full' // or 'partial'
324}
325```
326
327## Production Examples
328
329For complete, production-ready examples, see the collection packages in the TanStack DB repository:
330
331- **[@tanstack/query-collection](https://github.com/TanStack/db/tree/main/packages/query-collection)** - Pattern A: User-provided handlers with full refetch strategy
332- **[@tanstack/trailbase-collection](https://github.com/TanStack/db/tree/main/packages/trailbase-collection)** - Pattern B: Built-in handlers with ID-based tracking
333- **[@tanstack/electric-collection](https://github.com/TanStack/db/tree/main/packages/electric-collection)** - Pattern A: Transaction ID tracking with complex sync protocols
334
335### Key Lessons from Production Collections
336
337**From Query Collection:**
338- Simplest approach: Full refetch after mutations
339- Best for: APIs without real-time sync
340- Pattern: User provides `onInsert/onUpdate/onDelete` handlers
341
342**From Trailbase Collection:**
343- Shows ID-based optimistic state management
344- Handles provider batch limits (chunking large operations)
345- Pattern: Collection provides mutation handlers using record API
346
347**From Electric Collection:**
348- Complex transaction ID tracking for distributed sync
349- Demonstrates advanced deduplication techniques
350- Shows how to wrap user handlers with sync coordination
351
352## Complete Example: WebSocket Collection
353
354Here's a complete example of a WebSocket-based collection options creator that demonstrates the full round-trip flow:
355
3561. Client sends transaction with all mutations batched together
3572. Server processes the transaction and may modify the data (validation, timestamps, etc.)
3583. Server sends back acknowledgment and the actual processed data
3594. Client waits for this round-trip before dropping optimistic state
360
361```typescript
362import type {
363 CollectionConfig,
364 SyncConfig,
365 InsertMutationFnParams,
366 UpdateMutationFnParams,
367 DeleteMutationFnParams,
368 UtilsRecord
369} from '@tanstack/db'
370
371interface WebSocketMessage<T> {
372 type: 'insert' | 'update' | 'delete' | 'sync' | 'transaction' | 'ack'
373 data?: T | T[]
374 mutations?: Array<{
375 type: 'insert' | 'update' | 'delete'
376 data: T
377 id?: string
378 }>
379 transactionId?: string
380 id?: string
381}
382
383interface WebSocketCollectionConfig<TItem extends object>
384 extends Omit<CollectionConfig<TItem>, 'onInsert' | 'onUpdate' | 'onDelete' | 'sync'> {
385 url: string
386 reconnectInterval?: number
388 // Note: onInsert/onUpdate/onDelete are handled by the WebSocket connection
389 // Users don't provide these handlers
390}
391
392interface WebSocketUtils extends UtilsRecord {
393 reconnect: () => void
394 getConnectionState: () => 'connected' | 'disconnected' | 'connecting'
395}
396
397export function webSocketCollectionOptions<TItem extends object>(
398 config: WebSocketCollectionConfig<TItem>
399): CollectionConfig<TItem> & { utils: WebSocketUtils } {
400 let ws: WebSocket | null = null
401 let reconnectTimer: NodeJS.Timeout | null = null
402 let connectionState: 'connected' | 'disconnected' | 'connecting' = 'disconnected'
404 // Track pending transactions awaiting acknowledgment
405 const pendingTransactions = new Map<string, {
406 resolve: () => void
407 reject: (error: Error) => void
408 timeout: NodeJS.Timeout
409 }>()
411 const sync: SyncConfig<TItem>['sync'] = (params) => {
412 const { begin, write, commit, markReady } = params
414 function connect() {
415 connectionState = 'connecting'
416 ws = new WebSocket(config.url)
418 ws.onopen = () => {
419 connectionState = 'connected'
420 // Request initial sync
421 ws.send(JSON.stringify({ type: 'sync' }))
422 }
424 ws.onmessage = (event) => {
425 const message: WebSocketMessage<TItem> = JSON.parse(event.data)
427 switch (message.type) {
428 case 'sync':
429 // Initial sync with array of items
430 begin()
431 if (Array.isArray(message.data)) {
432 for (const item of message.data) {
433 write({ type: 'insert', value: item })
434 }
435 }
436 commit()
437 markReady()
438 break
440 case 'insert':
441 case 'update':
442 case 'delete':
443 // Real-time updates from other clients
444 begin()
445 write({
446 type: message.type,
447 value: message.data as TItem
448 })
449 commit()
450 break
452 case 'ack':
453 // Server acknowledged our transaction
454 if (message.transactionId) {
455 const pending = pendingTransactions.get(message.transactionId)
456 if (pending) {
457 clearTimeout(pending.timeout)
458 pendingTransactions.delete(message.transactionId)
459 pending.resolve()
460 }
461 }
462 break
464 case 'transaction':
465 // Server sending back the actual data after processing our transaction
466 if (message.mutations) {
467 begin()
468 for (const mutation of message.mutations) {
469 write({
470 type: mutation.type,
471 value: mutation.data
472 })
473 }
474 commit()
475 }
476 break
477 }
478 }
480 ws.onerror = (error) => {
481 console.error('WebSocket error:', error)
482 connectionState = 'disconnected'
483 }
485 ws.onclose = () => {
486 connectionState = 'disconnected'
487 // Auto-reconnect
488 if (!reconnectTimer) {
489 reconnectTimer = setTimeout(() => {
490 reconnectTimer = null
491 connect()
492 }, config.reconnectInterval || 5000)
493 }
494 }
495 }
497 // Start connection
498 connect()
500 // Return cleanup function
501 return () => {
502 if (reconnectTimer) {
503 clearTimeout(reconnectTimer)
504 reconnectTimer = null
505 }
506 if (ws) {
507 ws.close()
508 ws = null
509 }
510 }
511 }
513 // Helper function to send transaction and wait for server acknowledgment
514 const sendTransaction = async (
515 params: InsertMutationFnParams<TItem> | UpdateMutationFnParams<TItem> | DeleteMutationFnParams<TItem>
516 ): Promise<void> => {
517 if (ws?.readyState !== WebSocket.OPEN) {
518 throw new Error('WebSocket not connected')
519 }
521 const transactionId = crypto.randomUUID()
523 // Convert all mutations in the transaction to the wire format
524 const mutations = params.transaction.mutations.map(mutation => ({
525 type: mutation.type,
526 id: mutation.key,
527 data: mutation.type === 'delete' ? undefined :
528 mutation.type === 'update' ? mutation.changes :
529 mutation.modified
530 }))
532 // Send the entire transaction at once
533 ws.send(JSON.stringify({
534 type: 'transaction',
535 transactionId,
536 mutations
537 }))
539 // Wait for server acknowledgment
540 return new Promise<void>((resolve, reject) => {
541 const timeout = setTimeout(() => {
542 pendingTransactions.delete(transactionId)
543 reject(new Error(`Transaction ${transactionId} timed out`))
544 }, 10000) // 10 second timeout
546 pendingTransactions.set(transactionId, {
547 resolve,
548 reject,
549 timeout
550 })
551 })
552 }
554 // All mutation handlers use the same transaction sender
555 const onInsert = async (params: InsertMutationFnParams<TItem>) => {
556 await sendTransaction(params)
557 }
559 const onUpdate = async (params: UpdateMutationFnParams<TItem>) => {
560 await sendTransaction(params)
561 }
563 const onDelete = async (params: DeleteMutationFnParams<TItem>) => {
564 await sendTransaction(params)
565 }
567 return {
568 id: config.id,
569 schema: config.schema,
570 getKey: config.getKey,
571 sync: { sync },
572 onInsert,
573 onUpdate,
574 onDelete,
575 utils: {
576 reconnect: () => {
577 if (ws) ws.close()
578 connect()
579 },
580 getConnectionState: () => connectionState
581 }
582 }
583}
584```
585
586## Usage Example
587
588```typescript
589import { createCollection } from '@tanstack/react-db'
590import { webSocketCollectionOptions } from './websocket-collection'
591
592const todos = createCollection(
593 webSocketCollectionOptions({
594 url: 'ws://localhost:8080/todos',
595 getKey: (todo) => todo.id,
596 schema: todoSchema
597 // Note: No onInsert/onUpdate/onDelete - handled by WebSocket automatically
598 })
599)
600
601// Use the collection
602todos.insert({ id: '1', text: 'Buy milk', completed: false })
603
604// Access utilities
605todos.utils.getConnectionState() // 'connected'
606todos.utils.reconnect() // Force reconnect
607```
608
609## Advanced: Managing Optimistic State
610
611A critical challenge in sync-first apps is knowing when to drop optimistic state. When a user makes a change:
612
6131. The UI updates immediately (optimistic update)
6142. A mutation is sent to the backend
6153. The backend processes and persists the change
6164. The change syncs back to the client
6175. The optimistic state should be dropped in favor of the synced data
618
619The key question is: **How do you know when step 4 is complete?**
620
621### Strategy 1: Built-in Provider Methods (Recommended)
622
623Many providers offer built-in methods to wait for sync completion:
624
625```typescript
626// Firebase
627await waitForPendingWrites(firestore)
628
629// Custom WebSocket
630await websocket.waitForAck(transactionId)
631```
632
633### Strategy 2: Transaction ID Tracking (ElectricSQL)
634
635ElectricSQL returns transaction IDs that you can track:
636
637```typescript
638// Track seen transaction IDs
639const seenTxids = new Store<Set<number>>(new Set())
640
641// In sync, track txids from incoming messages
642if (message.headers.txids) {
643 message.headers.txids.forEach(txid => {
644 seenTxids.setState(prev => new Set([...prev, txid]))
645 })
646}
647
648// Mutation handlers return txids and wait for them
649const wrappedOnInsert = async (params) => {
650 const result = await config.onInsert!(params)
652 // Wait for the txid to appear in synced data
653 if (result.txid) {
654 await awaitTxId(result.txid)
655 }
657 return result
658}
659
660// Utility function to wait for a txid
661const awaitTxId = (txId: number): Promise<boolean> => {
662 if (seenTxids.state.has(txId)) return Promise.resolve(true)
664 return new Promise((resolve) => {
665 const unsubscribe = seenTxids.subscribe(() => {
666 if (seenTxids.state.has(txId)) {
667 unsubscribe()
668 resolve(true)
669 }
670 })
671 })
672}
673```
674
675### Strategy 3: ID-Based Tracking (Trailbase)
676
677Trailbase tracks when specific record IDs have been synced:
678
679```typescript
680// Track synced IDs with timestamps
681const seenIds = new Store(new Map<string, number>())
682
683// In sync, mark IDs as seen
684write({ type: 'insert', value: item })
685seenIds.setState(prev => new Map(prev).set(item.id, Date.now()))
686
687// Wait for specific IDs after mutations
688const wrappedOnInsert = async (params) => {
689 const ids = await config.recordApi.createBulk(items)
691 // Wait for all IDs to be synced back
692 await awaitIds(ids)
693}
694
695const awaitIds = (ids: string[]): Promise<void> => {
696 const allSynced = ids.every(id => seenIds.state.has(id))
697 if (allSynced) return Promise.resolve()
699 return new Promise((resolve) => {
700 const unsubscribe = seenIds.subscribe((state) => {
701 if (ids.every(id => state.has(id))) {
702 unsubscribe()
703 resolve()
704 }
705 })
706 })
707}
708```
709
710### Strategy 4: Version/Timestamp Tracking
711
712Track version numbers or timestamps to detect when data is fresh:
713
714```typescript
715// Track latest sync timestamp
716let lastSyncTime = 0
717
718// In mutations, record when the operation was sent
719const wrappedOnUpdate = async (params) => {
720 const mutationTime = Date.now()
721 await config.onUpdate(params)
723 // Wait for sync to catch up
724 await waitForSync(mutationTime)
725}
726
727const waitForSync = (afterTime: number): Promise<void> => {
728 if (lastSyncTime > afterTime) return Promise.resolve()
730 return new Promise((resolve) => {
731 const check = setInterval(() => {
732 if (lastSyncTime > afterTime) {
733 clearInterval(check)
734 resolve()
735 }
736 }, 100)
737 })
738}
739```
740
741### Strategy 5: Full Refetch (Query Collection)
742
743The query collection simply refetches all data after mutations:
744
745```typescript
746const wrappedOnInsert = async (params) => {
747 // Perform the mutation
748 await config.onInsert(params)
750 // Refetch the entire collection
751 await refetch()
753 // The refetch will trigger sync with fresh data,
754 // automatically dropping optimistic state
755}
756```
757
758### Choosing a Strategy
759
760- **Built-in Methods**: Best when your provider offers sync completion APIs
761- **Transaction IDs**: Best when your backend provides reliable transaction tracking
762- **ID-Based**: Good for systems where each mutation returns the affected IDs
763- **Full Refetch**: Simplest but least efficient; good for small datasets
764- **Version/Timestamp**: Works when your sync includes reliable ordering information
765
766### Implementation Tips
767
7681. **Always wait for sync** in your mutation handlers to ensure optimistic state is properly managed
7692. **Handle timeouts** - Don't wait forever for sync confirmation
7703. **Clean up tracking data** - Remove old txids/IDs to prevent memory leaks
7714. **Provide utilities** - Export functions like `awaitTxId` or `awaitSync` for advanced use cases
772
773## Best Practices
774
7751. **Always call markReady()** - This signals that the collection has initial data and is ready for use
7762. **Handle errors gracefully** - Call markReady() even on error to avoid blocking the app
7773. **Clean up resources** - Return a cleanup function from sync to prevent memory leaks
7784. **Batch operations** - Use begin/commit to batch multiple changes for better performance
7795. **Race Conditions** - Start listeners before initial fetch and buffer events
7806. **Type safety** - Use TypeScript generics to maintain type safety throughout
7817. **Provide utilities** - Export sync-engine-specific utilities for advanced use cases
782
783## Testing Your Collection
784
785Test your collection options creator with:
786
7871. **Unit tests** - Test sync logic, data transformations
7882. **Integration tests** - Test with real sync engine
7893. **Error scenarios** - Connection failures, invalid data
7904. **Performance** - Large datasets, frequent updates
791
792## Conclusion
793
794Creating a collection options creator allows you to integrate any sync engine with TanStack DB's powerful sync-first architecture. Follow the patterns shown here, and you'll have a robust, type-safe integration that provides excellent developer experience.