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: { id: string }) => 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: { id: string }) => 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
350An on-demand Collection with managed SQLite persistence can also replace its
351Electric provider session within the same Collection sync run when its cached
352resume evidence becomes invalid or its cache claim expires. This replacement
353rejects pending `awaitTxId` and `awaitMatch` waits with `StreamAbortedError`.
354A mutation handler waiting on one of them rejects; a later handler can wait for
355evidence from the replacement session. The replacement reloads demanded
356subsets and does not treat acknowledgements from the retired session as current.
357
358Before constructing a replacement `ShapeStream`, Electric releases the
359adapter-owned resources of the retired provider session, including its
360subscriptions and host lifecycle listeners. The replacement starts after cache
361rotation completes. An HTTP request that ignores cancellation may still finish
362later; its response cannot publish rows or settle waits for the replacement
363session.
364
365Persisted resumes wait for the cached row baseline to finish hydrating. If the
366persistence wrapper cannot verify hydration completion, Electric starts a fresh
367snapshot instead of using the saved offset and handle. It warns once per options
368descriptor; update the persistence adapter alongside Electric to enable safe resume.
369Fresh eager snapshots wait for hydration, then replace the cached rows at the
370snapshot's commit boundary. Rows omitted from that snapshot do not survive in
371the collection or its persisted cache, even when the fresh snapshot is empty.
372
373Tag membership is kept in memory, not restored from cached row headers. A cold
374restart cannot use a saved cursor that needs tags or comes from an older version
375that did not record whether tags were used. A changed shape, malformed saved
376state, or incomplete key-set evidence also invalidates the saved cursor.
377Untagged shapes with complete resume evidence can still resume from their saved
378offset.
379
380An eager persisted resume also needs compatible source progress when its adapter
381supplies that capability. Missing or incompatible progress requires a fresh
382snapshot, even with an explicit offset or handle. Those options do not certify
383the cached rows.
384An interrupted eager recovery keeps its durable reset marker. The next start
385also requires a fresh snapshot, even with an explicit offset or handle.
386
387Eager and progressive recovery fetch a full snapshot. Cached rows remain visible
388until that replacement completes; a partial batch or subset completion cannot
389publish it early. An on-demand collection with the current SQLite persistence
390wrapper instead retires the persisted cache generation and clears the source
391Collection's uncertified rows. A run with a valid claim can continue using the
392retired generation; new runs claim an empty generation. That local clear does
393not mark the Collection ready. Electric source evidence supplies readiness. It
394starts a changes-only stream at the current position and
395requests snapshots for active subset demands. Each demand completes after its
396snapshot rows apply, including an empty snapshot. Later demands cannot rehydrate
397old cache rows without a fresh source snapshot. With no active demand, recovery
398does not read all cached rows or download the full shape. The durable reset marker
399remains until a complete baseline can justify a global resume cursor. A cache
400generation created after claim expiry can lack that marker; its incompatible
401key-set evidence also requires scoped recovery on the next cold start, even
402when the caller supplies an explicit Electric offset or handle. Those source
403cursor options do not certify cached rows. A wrapper
404without scoped recovery support continues to use full-shape recovery. An
405interrupted recovery keeps the reset marker for the next start.
406Until a complete baseline is certified, each later cold start repeats scoped
407recovery. Uncertified cached rows from earlier starts are not shown offline.
408Retired new-format storage is reclaimed by the next cache-claim collection
409operation after its claims release or expire; clock passage alone does not
410run SQLite work. A paused run whose claim expires must reload its demanded
411subsets from the source when it resumes. Pre-upgrade on-demand storage is
412isolated but needs a separate cross-version cleanup policy while older tabs
413may still use it. Scoped recovery
414does not certify the new generation for offline reuse.
415
416With `initialRender: { strategy: 'network-first' }`, an on-demand or
417progressive Collection can render a demand offline from SQLite after that exact
418demand settled online in an earlier session. Each demand keeps its own
419coverage in the current persisted cache generation. Scoped recovery, cache-claim
420expiry, and a must-refetch end it, so after any of them a demand waits for the
421network again. A demand that loads during the rest of a scoped-recovery sync
422run records no coverage. See [On-demand Collections offline](../guides/sqlite-persistence.md#on-demand-collections-offline).
423
424During scoped recovery, coordinator notifications about SQLite changes do not
425hydrate, truncate, or replace public source rows. The Electric change stream
426and demanded source snapshots own those rows until the sync run ends. A change
427made in another tab may therefore become public when Electric delivers it,
428rather than when its durable-cache notification arrives. Outside scoped
429recovery, coordinator invalidation retains its normal behavior.
430
431An eager or progressive resume cannot apply a partial update to an unknown row.
432The adapter rejects that batch, stops the stream, and records a reset so the
433next sync starts from a full snapshot. Before the Collection is ready, this
434fails the first load (`status: 'error'`); after it, the rows stay and the
435source node shows an `error` in `collection.health` and in each live query's
436`health` tree. This does not silently retry the failed stream;
437`collection.reload()` refetches.
438
439While the Electric stream retries a failed request, the Collection reports
440nothing: it stays `loading` before its first up-to-date, and keeps its health tree
441unchanged afterward. When the stream gives up, it calls `fail()`: a failed first load
442before readiness, or the source node's `error` after it. Complete updates from an explicit `replica: 'full'` stream remain valid.
443On-demand streams can observe updates outside their loaded subsets; unknown
444partial rows are ignored, while transaction acknowledgement evidence is retained.
445Outside scoped recovery, complete rows published by persistence reloads or
446another tab are valid baselines for subsequent partial updates. Uncertified
447cached rows in scoped recovery are not. Pending deletions and resets still take
448precedence over an older row that remains publicly visible.
449
450Reusing Electric collection options, including a spread of those options, does
451not share transaction waiters or tag visibility between collections. Tag state
452survives a compatible resume of the same collection and clears on a fresh
453snapshot or `must-refetch`.
454
455### Helper Functions
456
457The package exports helper functions for use in custom match functions:
458
459- `isChangeMessage(message)`: Check if a message is a data change (insert/update/delete)
460- `isControlMessage(message)`: Check if a message is a control message (up-to-date, must-refetch)
461
462```typescript
463import { isChangeMessage, isControlMessage } from '@tanstack/electric-db-collection'
464
465// Use in custom match functions
466const matchFn = (message) => {
467 if (isChangeMessage(message)) {
468 return message.headers.operation === 'insert'
469 }
470 return false
471}
472```
473
474## Debugging
475
476### Common Issue: awaitTxId Stalls or Times Out
477
478A frequent issue developers encounter is that `awaitTxId` (or the transaction's `when('settled')`) stalls indefinitely, eventually timing out with no error messages. The data persists correctly to the database, but the optimistic mutation never resolves.
479
480**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.
481
482### Enable Debug Logging
483
484To diagnose txid issues, enable debug logging in your browser console:
485
486```javascript
487localStorage.debug = 'ts/db:electric'
488```
489
490This will show you when mutations start waiting for txids and when txids arrive from Electric's sync stream.
491
492This is powered by the [debug](https://www.npmjs.com/package/debug) package.
493
494**When txids DON'T match (common bug):**
495```
496ts/db:electric awaitTxId called with txid 124
497ts/db:electric new txids synced from pg [123]
498// Stalls forever - 124 never arrives!
499```
500
501In 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.
502
503**When txids DO match (correct):**
504```
505ts/db:electric awaitTxId called with txid 123
506ts/db:electric new txids synced from pg [123]
507ts/db:electric awaitTxId found match for txid 123
508// Resolves immediately!
509```
510
511### The Solution: Query txid Inside the Transaction
512
513You **must** call `pg_current_xact_id()` inside the same transaction as your mutation:
514
515**❌ Wrong - txid queried outside transaction:**
516```typescript
517// DON'T DO THIS
518async function createTodo(data) {
519 const txid = await generateTxId(sql) // Wrong: separate transaction
520
521 await sql.begin(async (tx) => {
522 await tx`INSERT INTO todos ${tx(data)}`
523 })
524
525 return { txid } // This txid won't match!
526}
527```
528
529**✅ Correct - txid queried inside transaction:**
530```typescript
531// DO THIS
532async function createTodo(data) {
533 let txid!: Txid
534
535 const result = await sql.begin(async (tx) => {
536 // Call generateTxId INSIDE the transaction
537 txid = await generateTxId(tx)
538
539 const [todo] = await tx`
540 INSERT INTO todos ${tx(data)}
541 RETURNING *
542 `
543 return todo
544 })
545
546 return { todo: result, txid } // txid matches the mutation
547}
548
549async function generateTxId(tx: any): Promise<Txid> {
550 const result = await tx`SELECT pg_current_xact_id()::xid::text as txid`
551 const txid = result[0]?.txid
552
553 if (txid === undefined) {
554 throw new Error(`Failed to get transaction ID`)
555 }
556
557 return parseInt(txid, 10)
558}
559```
560
561See working examples in:
562- `examples/react/todo/src/routes/api/todos.ts`
563- `examples/react/todo/src/api/server.ts`