Open History to see the last commit
1---
2title: Electric Collection
3---
4
5Electric collections provide seamless integration between TanStack DB and ElectricSQL, enabling real-time data synchronization with your Postgres database through Electric's sync engine.
6
7## Overview
8
9The `@tanstack/electric-db-collection` package allows you to create collections that:
10- Automatically sync data from Postgres via Electric shapes
11- Support optimistic updates with transaction matching and automatic rollback on errors
12- Handle persistence through customizable mutation handlers
13
14## Installation
15
16```bash
17npm install @tanstack/electric-db-collection @tanstack/react-db
18```
19
20## Basic Usage
21
22```typescript
23import { createCollection } from '@tanstack/react-db'
24import { electricCollectionOptions } from '@tanstack/electric-db-collection'
25
26const todosCollection = createCollection(
27 electricCollectionOptions({
28 shapeOptions: {
29 url: '/api/todos',
30 },
31 getKey: (item) => item.id,
32 })
33)
34```
35
36## Configuration Options
37
38The `electricCollectionOptions` function accepts the following options:
39
40### Required Options
41
42- `shapeOptions`: Configuration for the ElectricSQL ShapeStream
43 - `url`: The URL of your proxy to Electric
44
45- `getKey`: Function to extract the unique key from an item
46
47### Optional
48
49- `id`: Unique identifier for the collection
50- `schema`: Schema for validating items. Any Standard Schema compatible schema
51- `sync`: Custom sync configuration
52
53### Persistence Handlers
54
55Handlers are called before mutations to persist changes to your backend:
56
57- `onInsert`: Handler called before insert operations
58- `onUpdate`: Handler called before update operations
59- `onDelete`: Handler called before delete operations
60
61Each handler should call `await collection.utils.awaitTxId(txid)` to wait for synchronization. For cases where your API cannot return txids, use the `awaitMatch` utility function.
62
63## Persistence Handlers & Synchronization
64
65Handlers persist mutations to the backend and wait for Electric to sync the changes back. This prevents UI glitches where optimistic updates would be removed and then re-added. TanStack DB blocks sync data until the mutation is confirmed, ensuring smooth user experience.
66
67### 1. Using Txid (Recommended)
68
69The recommended approach uses PostgreSQL transaction IDs (txids) for precise matching. The backend returns a txid, and the client waits for that specific txid to appear in the Electric stream.
70
71```typescript
72const todosCollection = createCollection(
73 electricCollectionOptions({
74 id: 'todos',
75 schema: todoSchema,
76 getKey: (item) => item.id,
77 shapeOptions: {
78 url: '/api/todos',
79 params: { table: 'todos' },
80 },
81
82 onInsert: async ({ transaction, collection }) => {
83 const newItem = transaction.mutations[0].modified
84 const response = await api.todos.create(newItem)
85
86 // Wait for txid to sync
87 await collection.utils.awaitTxId(response.txid)
88 },
89
90 onUpdate: async ({ transaction, collection }) => {
91 const { original, changes } = transaction.mutations[0]
92 const response = await api.todos.update({
93 where: { id: original.id },
94 data: changes
95 })
96
97 // Wait for txid to sync
98 await collection.utils.awaitTxId(response.txid)
99 }
100 })
101)
102```
103
104### 2. Using Custom Match Functions
105
106For cases where txids aren't available, use the `awaitMatch` utility function to wait for synchronization with custom matching logic:
107
108```typescript
109import { isChangeMessage } from '@tanstack/electric-db-collection'
110
111const todosCollection = createCollection(
112 electricCollectionOptions({
113 id: 'todos',
114 getKey: (item) => item.id,
115 shapeOptions: {
116 url: '/api/todos',
117 params: { table: 'todos' },
118 },
119
120 onInsert: async ({ transaction, collection }) => {
121 const newItem = transaction.mutations[0].modified
122 await api.todos.create(newItem)
123
124 // Use awaitMatch utility for custom matching
125 await collection.utils.awaitMatch(
126 (message) => {
127 return isChangeMessage(message) &&
128 message.headers.operation === 'insert' &&
129 message.value.text === newItem.text
130 },
131 5000 // timeout in ms (optional, defaults to 15000)
132 )
133 }
134 })
135)
136```
137
138### 3. Using Simple Timeout
139
140For quick prototyping or when you're confident about timing, you can use a simple timeout. This is crude but works as almost always the data will be synced back in under 2 seconds:
141
142```typescript
143const todosCollection = createCollection(
144 electricCollectionOptions({
145 id: 'todos',
146 getKey: (item) => item.id,
147 shapeOptions: {
148 url: '/api/todos',
149 params: { table: 'todos' },
150 },
151
152 onInsert: async ({ transaction }) => {
153 const newItem = transaction.mutations[0].modified
154 await api.todos.create(newItem)
155
156 // Simple timeout approach
157 await new Promise(resolve => setTimeout(resolve, 2000))
158 }
159 })
160)
161```
162
163On the backend, you can extract the `txid` for a transaction by querying Postgres directly.
164
165```ts
166async function generateTxId(tx) {
167 // The ::xid cast strips off the epoch, giving you the raw 32-bit value
168 // that matches what PostgreSQL sends in logical replication streams
169 // (and then exposed through Electric which we'll match against
170 // in the client).
171 const result = await tx.execute(
172 sql`SELECT pg_current_xact_id()::xid::text as txid`
173 )
174 const txid = result.rows[0]?.txid
175
176 if (txid === undefined) {
177 throw new Error(`Failed to get transaction ID`)
178 }
179
180 return parseInt(txid as string, 10)
181}
182```
183
184### Electric Proxy Example
185
186Electric is typically deployed behind a proxy server that handles shape configuration, authentication and authorization. This provides better security and allows you to control what data users can access without exposing Electric to the client.
187
188
189Here is an example proxy implementation using TanStack Start:
190
191```typescript
192import { createServerFileRoute } from "@tanstack/react-start/server"
193import { ELECTRIC_PROTOCOL_QUERY_PARAMS } from "@electric-sql/client"
194
195// Electric URL
196const baseUrl = 'http://.../v1/shape'
197
198const serve = async ({ request }: { request: Request }) => {
199 // ...check user authorization
200 const url = new URL(request.url)
201 const originUrl = new URL(baseUrl)
202
203 // passthrough parameters from electric client
204 url.searchParams.forEach((value, key) => {
205 if (ELECTRIC_PROTOCOL_QUERY_PARAMS.includes(key)) {
206 originUrl.searchParams.set(key, value)
207 }
208 })
209
210 // set shape parameters
211 // full spec: https://github.com/electric-sql/electric/blob/main/website/electric-api.yaml
212 originUrl.searchParams.set("table", "todos")
213 // Where clause to filter rows in the table (optional).
214 // originUrl.searchParams.set("where", "completed = true")
216 // Select the columns to sync (optional)
217 // originUrl.searchParams.set("columns", "id,text,completed")
218
219 const response = await fetch(originUrl)
220 const headers = new Headers(response.headers)
221 headers.delete("content-encoding")
222 headers.delete("content-length")
223
224 return new Response(response.body, {
225 status: response.status,
226 statusText: response.statusText,
227 headers,
228 })
229}
230
231export const ServerRoute = createServerFileRoute("/api/todos").methods({
232 GET: serve,
233})
234```
235
236## Optimistic Updates with Explicit Transactions
237
238For more advanced use cases, you can create custom actions that can do multiple mutations across collections transactionally. You can use the utility methods to wait for synchronization with different strategies:
239
240### Using Txid Strategy
241
242```typescript
243const addTodoAction = createOptimisticAction({
244 onMutate: ({ text }) => {
245 // optimistically insert with a temporary ID
246 const tempId = crypto.randomUUID()
247 todosCollection.insert({
248 id: tempId,
249 text,
250 completed: false,
251 created_at: new Date(),
252 })
254 // ... mutate other collections
255 },
257 mutationFn: async ({ text }) => {
258 const response = await api.todos.create({
259 data: { text, completed: false }
260 })
262 // Wait for the specific txid
263 await todosCollection.utils.awaitTxId(response.txid)
264 }
265})
266```
267
268### Using Custom Match Function
269
270```typescript
271import { isChangeMessage } from '@tanstack/electric-db-collection'
272
273const addTodoAction = createOptimisticAction({
274 onMutate: ({ text }) => {
275 const tempId = crypto.randomUUID()
276 todosCollection.insert({
277 id: tempId,
278 text,
279 completed: false,
280 created_at: new Date(),
281 })
282 },
284 mutationFn: async ({ text }) => {
285 await api.todos.create({
286 data: { text, completed: false }
287 })
289 // Wait for matching message
290 await todosCollection.utils.awaitMatch(
291 (message) => {
292 return isChangeMessage(message) &&
293 message.headers.operation === 'insert' &&
294 message.value.text === text
295 }
296 )
297 }
298})
299```
300
301## Utility Methods
302
303The collection provides these utility methods via `collection.utils`:
304
305### `awaitTxId(txid, timeout?)`
306
307Wait for a specific transaction ID to be synchronized:
308
309```typescript
310// Wait for specific txid
311await todosCollection.utils.awaitTxId(12345)
312
313// With custom timeout (default is 15 seconds)
314await todosCollection.utils.awaitTxId(12345, 10000)
315```
316
317This is useful when you need to ensure a mutation has been synchronized before proceeding with other operations.
318
319For a collection wrapped with SQLite persistence, `awaitTxId` observes the
320transaction in the Electric stream. It can resolve before the local SQLite
321write completes. Do not use it as a local durability acknowledgment: if the
322page closes in that gap, reopening may need Electric to recover the row.
323
324### `awaitMatch(matchFn, timeout?)`
325
326Wait for a custom match function to find a matching message:
327
328```typescript
329import { isChangeMessage } from '@tanstack/electric-db-collection'
330
331// Wait for a specific message pattern
332await todosCollection.utils.awaitMatch(
333 (message) => {
334 return isChangeMessage(message) &&
335 message.headers.operation === 'insert' &&
336 message.value.text === 'New Todo'
337 },
338 5000 // timeout in ms
339)
340```
341
342### Cleanup and resume safety
343
344Transaction evidence and pending `awaitTxId`/`awaitMatch` calls belong to one
345collection lifecycle. Explicit cleanup and automatic garbage collection reject
346pending waits with `StreamAbortedError`; callbacks from the retired stream cannot
347settle waits in a restarted collection. Observe these promises even when the
348component or collection may be disposed before they settle.
349
350Persisted resumes wait for the cached row baseline to finish hydrating. If the
351persistence wrapper cannot verify hydration completion, Electric starts a fresh
352snapshot instead of using the saved offset and handle. It warns once per options
353descriptor; update the persistence adapter alongside Electric to enable safe resume.
354Fresh eager snapshots wait for hydration, then replace the cached rows at the
355snapshot's commit boundary. Rows omitted from that snapshot do not survive in
356the collection or its persisted cache, even when the fresh snapshot is empty.
357
358Tag membership is kept in memory, not restored from cached row headers. A cold
359restart therefore fetches a full snapshot when the saved state needs tags, or
360comes from an older version that did not record whether tags were used. Untagged
361shapes can still resume from their saved offset. Cached rows remain visible until
362the replacement snapshot completes; a partial batch or subset completion cannot
363publish that replacement early. Interrupting recovery leaves a durable reset
364marker so the next start still refetches. This recovery also requests a full shape
365snapshot in on-demand mode, at the cost of fetching more than the active subsets.
366
367An eager or progressive resume cannot apply a partial update to an unknown row.
368The adapter rejects that batch, enters an error state, and records a reset so the
369next sync starts from a full snapshot. This does not silently retry the failed
370stream. Complete updates from an explicit `replica: 'full'` stream remain valid.
371On-demand streams can observe updates outside their loaded subsets; unknown
372partial rows are ignored, while transaction acknowledgement evidence is retained.
373Complete rows published by persistence reloads or another tab are valid baselines
374for subsequent partial updates. Pending deletions and resets still take precedence
375over an older row that remains publicly visible.
376
377Reusing Electric collection options, including a spread of those options, does
378not share transaction waiters or tag visibility between collections. Tag state
379survives a compatible resume of the same collection and clears on a fresh
380snapshot or `must-refetch`.
381
382### Helper Functions
383
384The package exports helper functions for use in custom match functions:
385
386- `isChangeMessage(message)`: Check if a message is a data change (insert/update/delete)
387- `isControlMessage(message)`: Check if a message is a control message (up-to-date, must-refetch)
388
389```typescript
390import { isChangeMessage, isControlMessage } from '@tanstack/electric-db-collection'
391
392// Use in custom match functions
393const matchFn = (message) => {
394 if (isChangeMessage(message)) {
395 return message.headers.operation === 'insert'
396 }
397 return false
398}
399```
400
401## Debugging
402
403### Common Issue: awaitTxId Stalls or Times Out
404
405A frequent issue developers encounter is that `awaitTxId` (or the transaction's `isPersisted.promise`) stalls indefinitely, eventually timing out with no error messages. The data persists correctly to the database, but the optimistic mutation never resolves.
406
407**Root Cause:** This happens when the transaction ID (txid) returned from your API doesn't match the actual transaction ID of the mutation in Postgres. This mismatch occurs when you query `pg_current_xact_id()` **outside** the same transaction that performs the mutation.
408
409### Enable Debug Logging
410
411To diagnose txid issues, enable debug logging in your browser console:
412
413```javascript
414localStorage.debug = 'ts/db:electric'
415```
416
417This will show you when mutations start waiting for txids and when txids arrive from Electric's sync stream.
418
419This is powered by the [debug](https://www.npmjs.com/package/debug) package.
420
421**When txids DON'T match (common bug):**
422```
423ts/db:electric awaitTxId called with txid 124
424ts/db:electric new txids synced from pg [123]
425// Stalls forever - 124 never arrives!
426```
427
428In this example, the mutation happened in transaction 123, but you queried `pg_current_xact_id()` in a separate transaction (124) that ran after the mutation. The client waits for 124 which will never arrive.
429
430**When txids DO match (correct):**
431```
432ts/db:electric awaitTxId called with txid 123
433ts/db:electric new txids synced from pg [123]
434ts/db:electric awaitTxId found match for txid 123
435// Resolves immediately!
436```
437
438### The Solution: Query txid Inside the Transaction
439
440You **must** call `pg_current_xact_id()` inside the same transaction as your mutation:
441
442**❌ Wrong - txid queried outside transaction:**
443```typescript
444// DON'T DO THIS
445async function createTodo(data) {
446 const txid = await generateTxId(sql) // Wrong: separate transaction
447
448 await sql.begin(async (tx) => {
449 await tx`INSERT INTO todos ${tx(data)}`
450 })
451
452 return { txid } // This txid won't match!
453}
454```
455
456**✅ Correct - txid queried inside transaction:**
457```typescript
458// DO THIS
459async function createTodo(data) {
460 let txid!: Txid
461
462 const result = await sql.begin(async (tx) => {
463 // Call generateTxId INSIDE the transaction
464 txid = await generateTxId(tx)
465
466 const [todo] = await tx`
467 INSERT INTO todos ${tx(data)}
468 RETURNING *
469 `
470 return todo
471 })
472
473 return { todo: result, txid } // txid matches the mutation
474}
475
476async function generateTxId(tx: any): Promise<Txid> {
477 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
478 const txid = result[0]?.txid
479
480 if (txid === undefined) {
481 throw new Error(`Failed to get transaction ID`)
482 }
483
484 return parseInt(txid, 10)
485}
486```
487
488See working examples in:
489- `examples/react/todo/src/routes/api/todos.ts`
490- `examples/react/todo/src/api/server.ts`