Open History to see the last commit
1---
2title: Electric Collection
3---
4
5# Electric Collection
6
7Electric collections provide seamless integration between TanStack DB and ElectricSQL, enabling real-time data synchronization with your Postgres database through Electric's sync engine.
8
9## Overview
10
11The `@tanstack/electric-db-collection` package allows you to create collections that:
12- Automatically sync data from Postgres via Electric shapes
13- Support optimistic updates with transaction matching and automatic rollback on errors
14- Handle persistence through customizable mutation handlers
15
16## Installation
17
18```bash
19npm install @tanstack/electric-db-collection @tanstack/react-db
20```
21
22## Basic Usage
23
24```typescript
25import { createCollection } from '@tanstack/react-db'
26import { electricCollectionOptions } from '@tanstack/electric-db-collection'
27
28const todosCollection = createCollection(
29 electricCollectionOptions({
30 shapeOptions: {
31 url: '/api/todos',
32 },
33 getKey: (item) => item.id,
34 })
35)
36```
37
38## Configuration Options
39
40The `electricCollectionOptions` function accepts the following options:
41
42### Required Options
43
44- `shapeOptions`: Configuration for the ElectricSQL ShapeStream
45 - `url`: The URL of your proxy to Electric
46
47- `getKey`: Function to extract the unique key from an item
48
49### Optional
50
51- `id`: Unique identifier for the collection
52- `schema`: Schema for validating items. Any Standard Schema compatible schema
53- `sync`: Custom sync configuration
54
55### Persistence Handlers
56
57Handlers are called before mutations to persist changes to your backend:
58
59- `onInsert`: Handler called before insert operations
60- `onUpdate`: Handler called before update operations
61- `onDelete`: Handler called before delete operations
62
63Each handler should return `{ txid }` to wait for synchronization. For cases where your API can not return txids, use the `awaitMatch` utility function.
64
65## Persistence Handlers & Synchronization
66
67Handlers 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.
68
69### 1. Using Txid (Recommended)
70
71The 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.
72
73```typescript
74const todosCollection = createCollection(
75 electricCollectionOptions({
76 id: 'todos',
77 schema: todoSchema,
78 getKey: (item) => item.id,
79 shapeOptions: {
80 url: '/api/todos',
81 params: { table: 'todos' },
82 },
83
84 onInsert: async ({ transaction }) => {
85 const newItem = transaction.mutations[0].modified
86 const response = await api.todos.create(newItem)
87
88 // Return txid to wait for sync
89 return { txid: response.txid }
90 },
91
92 onUpdate: async ({ transaction }) => {
93 const { original, changes } = transaction.mutations[0]
94 const response = await api.todos.update({
95 where: { id: original.id },
96 data: changes
97 })
98
99 return { txid: response.txid }
100 }
101 })
102)
103```
104
105### 2. Using Custom Match Functions
106
107For cases where txids aren't available, use the `awaitMatch` utility function to wait for synchronization with custom matching logic:
108
109```typescript
110import { isChangeMessage } from '@tanstack/electric-db-collection'
111
112const todosCollection = createCollection(
113 electricCollectionOptions({
114 id: 'todos',
115 getKey: (item) => item.id,
116 shapeOptions: {
117 url: '/api/todos',
118 params: { table: 'todos' },
119 },
120
121 onInsert: async ({ transaction, collection }) => {
122 const newItem = transaction.mutations[0].modified
123 await api.todos.create(newItem)
124
125 // Use awaitMatch utility for custom matching
126 await collection.utils.awaitMatch(
127 (message) => {
128 return isChangeMessage(message) &&
129 message.headers.operation === 'insert' &&
130 message.value.text === newItem.text
131 },
132 5000 // timeout in ms (optional, defaults to 3000)
133 )
134 }
135 })
136)
137```
138
139### 3. Using Simple Timeout
140
141For 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:
142
143```typescript
144const todosCollection = createCollection(
145 electricCollectionOptions({
146 id: 'todos',
147 getKey: (item) => item.id,
148 shapeOptions: {
149 url: '/api/todos',
150 params: { table: 'todos' },
151 },
152
153 onInsert: async ({ transaction }) => {
154 const newItem = transaction.mutations[0].modified
155 await api.todos.create(newItem)
156
157 // Simple timeout approach
158 await new Promise(resolve => setTimeout(resolve, 2000))
159 }
160 })
161)
162```
163
164On the backend, you can extract the `txid` for a transaction by querying Postgres directly.
165
166```ts
167async function generateTxId(tx) {
168 // The ::xid cast strips off the epoch, giving you the raw 32-bit value
169 // that matches what PostgreSQL sends in logical replication streams
170 // (and then exposed through Electric which we'll match against
171 // in the client).
172 const result = await tx.execute(
173 sql`SELECT pg_current_xact_id()::xid::text as txid`
174 )
175 const txid = result.rows[0]?.txid
176
177 if (txid === undefined) {
178 throw new Error(`Failed to get transaction ID`)
179 }
180
181 return parseInt(txid as string, 10)
182}
183```
184
185### Electric Proxy Example
186
187Electric 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.
188
189
190Here is an example proxy implementation using TanStack Start:
191
192```typescript
193import { createServerFileRoute } from "@tanstack/react-start/server"
194import { ELECTRIC_PROTOCOL_QUERY_PARAMS } from "@electric-sql/client"
195
196// Electric URL
197const baseUrl = 'http://.../v1/shape'
198
199const serve = async ({ request }: { request: Request }) => {
200 // ...check user authorization
201 const url = new URL(request.url)
202 const originUrl = new URL(baseUrl)
203
204 // passthrough parameters from electric client
205 url.searchParams.forEach((value, key) => {
206 if (ELECTRIC_PROTOCOL_QUERY_PARAMS.includes(key)) {
207 originUrl.searchParams.set(key, value)
208 }
209 })
210
211 // set shape parameters
212 // full spec: https://github.com/electric-sql/electric/blob/main/website/electric-api.yaml
213 originUrl.searchParams.set("table", "todos")
214 // Where clause to filter rows in the table (optional).
215 // originUrl.searchParams.set("where", "completed = true")
217 // Select the columns to sync (optional)
218 // originUrl.searchParams.set("columns", "id,text,completed")
219
220 const response = await fetch(originUrl)
221 const headers = new Headers(response.headers)
222 headers.delete("content-encoding")
223 headers.delete("content-length")
224
225 return new Response(response.body, {
226 status: response.status,
227 statusText: response.statusText,
228 headers,
229 })
230}
231
232export const ServerRoute = createServerFileRoute("/api/todos").methods({
233 GET: serve,
234})
235```
236
237## Optimistic Updates with Explicit Transactions
238
239For 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:
240
241### Using Txid Strategy
242
243```typescript
244const addTodoAction = createOptimisticAction({
245 onMutate: ({ text }) => {
246 // optimistically insert with a temporary ID
247 const tempId = crypto.randomUUID()
248 todosCollection.insert({
249 id: tempId,
250 text,
251 completed: false,
252 created_at: new Date(),
253 })
255 // ... mutate other collections
256 },
258 mutationFn: async ({ text }) => {
259 const response = await api.todos.create({
260 data: { text, completed: false }
261 })
263 // Wait for the specific txid
264 await todosCollection.utils.awaitTxId(response.txid)
265 }
266})
267```
268
269### Using Custom Match Function
270
271```typescript
272import { isChangeMessage } from '@tanstack/electric-db-collection'
273
274const addTodoAction = createOptimisticAction({
275 onMutate: ({ text }) => {
276 const tempId = crypto.randomUUID()
277 todosCollection.insert({
278 id: tempId,
279 text,
280 completed: false,
281 created_at: new Date(),
282 })
283 },
285 mutationFn: async ({ text }) => {
286 await api.todos.create({
287 data: { text, completed: false }
288 })
290 // Wait for matching message
291 await todosCollection.utils.awaitMatch(
292 (message) => {
293 return isChangeMessage(message) &&
294 message.headers.operation === 'insert' &&
295 message.value.text === text
296 }
297 )
298 }
299})
300```
301
302## Utility Methods
303
304The collection provides these utility methods via `collection.utils`:
305
306### `awaitTxId(txid, timeout?)`
307
308Manually wait for a specific transaction ID to be synchronized:
309
310```typescript
311// Wait for specific txid
312await todosCollection.utils.awaitTxId(12345)
313
314// With custom timeout (default is 5 seconds)
315await todosCollection.utils.awaitTxId(12345, 10000)
316```
317
318This is useful when you need to ensure a mutation has been synchronized before proceeding with other operations.
319
320### `awaitMatch(matchFn, timeout?)`
321
322Manually wait for a custom match function to find a matching message:
323
324```typescript
325import { isChangeMessage } from '@tanstack/electric-db-collection'
326
327// Wait for a specific message pattern
328await todosCollection.utils.awaitMatch(
329 (message) => {
330 return isChangeMessage(message) &&
331 message.headers.operation === 'insert' &&
332 message.value.text === 'New Todo'
333 },
334 5000 // timeout in ms
335)
336```
337
338### Helper Functions
339
340The package exports helper functions for use in custom match functions:
341
342- `isChangeMessage(message)`: Check if a message is a data change (insert/update/delete)
343- `isControlMessage(message)`: Check if a message is a control message (up-to-date, must-refetch)
344
345```typescript
346import { isChangeMessage, isControlMessage } from '@tanstack/electric-db-collection'
347
348// Use in custom match functions
349const matchFn = (message) => {
350 if (isChangeMessage(message)) {
351 return message.headers.operation === 'insert'
352 }
353 return false
354}
355```
356
357## Debugging
358
359### Common Issue: awaitTxId Stalls or Times Out
360
361A 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.
362
363**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.
364
365### Enable Debug Logging
366
367To diagnose txid issues, enable debug logging in your browser console:
368
369```javascript
370localStorage.debug = 'ts/db:electric'
371```
372
373This will show you when mutations start waiting for txids and when txids arrive from Electric's sync stream.
374
375This is powered by the [debug](https://www.npmjs.com/package/debug) package.
376
377**When txids DON'T match (common bug):**
378```
379ts/db:electric awaitTxId called with txid 124
380ts/db:electric new txids synced from pg [123]
381// Stalls forever - 124 never arrives!
382```
383
384In 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.
385
386**When txids DO match (correct):**
387```
388ts/db:electric awaitTxId called with txid 123
389ts/db:electric new txids synced from pg [123]
390ts/db:electric awaitTxId found match for txid 123
391// Resolves immediately!
392```
393
394### The Solution: Query txid Inside the Transaction
395
396You **must** call `pg_current_xact_id()` inside the same transaction as your mutation:
397
398**❌ Wrong - txid queried outside transaction:**
399```typescript
400// DON'T DO THIS
401async function createTodo(data) {
402 const txid = await generateTxId(sql) // Wrong: separate transaction
403
404 await sql.begin(async (tx) => {
405 await tx`INSERT INTO todos ${tx(data)}`
406 })
407
408 return { txid } // This txid won't match!
409}
410```
411
412**✅ Correct - txid queried inside transaction:**
413```typescript
414// DO THIS
415async function createTodo(data) {
416 let txid!: Txid
417
418 const result = await sql.begin(async (tx) => {
419 // Call generateTxId INSIDE the transaction
420 txid = await generateTxId(tx)
421
422 const [todo] = await tx`
423 INSERT INTO todos ${tx(data)}
424 RETURNING *
425 `
426 return todo
427 })
428
429 return { todo: result, txid } // txid matches the mutation
430}
431
432async function generateTxId(tx: any): Promise<Txid> {
433 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
434 const txid = result[0]?.txid
435
436 if (txid === undefined) {
437 throw new Error(`Failed to get transaction ID`)
438 }
439
440 return parseInt(txid, 10)
441}
442```
443
444See working examples in:
445- `examples/react/todo/src/routes/api/todos.ts`
446- `examples/react/todo/src/api/server.ts`