docs: add Neon Realtime collection guide #2308
OpenKyleAMathewswants to merge 3 commits into
main fromcodex/neon-realtime-docsopened - @@ -0,0 +3,21 @@3+---4+5+Neon Realtime collections integrate TanStack DB with [Neon Realtime](https://neon.com/docs/realtime/overview), syncing the results of live SQL queries from Postgres into client-side collections.6+7+## Overview8+9+The `@neon/realtime-tanstack` package, maintained by Neon, allows you to create collections that:10+11+Sync live SQL query results, including joins, aggregates, ordering, and limits12+Apply complete query results and committed change batches atomically13+Support local live queries with filters, sorts, and joins across collections14+Handle optimistic updates with transaction ID matching and automatic rollback on errors15+16+Neon Realtime is currently in beta. Follow the [Neon Realtime quickstart](https://neon.com/docs/realtime/quickstart) to enable it on your branch and configure your application's allowed origins before creating a collection.17+18+## Installation19+20+Install the Realtime SDK, its TanStack DB adapter, and your framework integration. The examples below use React:21+22+```bash23+npm install @neon/realtime @neon/realtime-tanstack @tanstack/react-dbdocs/collections/neon-realtime-collection.md lines 91 to 95OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +75,21 @@75+import type { Todo } from './types'76+77+const client = createRealtimeClient({78+ url: 'YOUR_NEON_REALTIME_URL',79+})80+81+async function fetchTodosQuery(): Promise<SealedLiveQuery<Todo>> {82+ const response = await fetch('/api/todos/live', { method: 'POST' })83+84+ if (!response.ok) {85+ throw new Error(`Could not fetch the todos query (${response.status})`)86+ }87+88+ return response.json()89+}90+91+export const todosCollection = createCollection(92+ realtimeCollectionOptions({93+ id: 'todos',94+ client,95+ query: await fetchTodosQuery(),@@ -0,0 +195,21 @@195+After the backend commits a write, wait for its Postgres transaction ID with `collection.utils.awaitTxId(txid, timeout)`. This keeps the optimistic state until the corresponding synced changes have entered TanStack DB's sync queue.196+197+For example, add these handlers to the collection options above. The application API functions shown here send each batch in one request and return `{ txid: string | null }`, with `null` when no rows changed:198+199+```ts200+import { createCollection } from '@tanstack/react-db'201+import { realtimeCollectionOptions } from '@neon/realtime-tanstack'202+import { api } from './api'203+import type { Todo } from './types'204+205+export const todosCollection = createCollection(206+ realtimeCollectionOptions({207+ id: 'todos',208+ client,209+ query: await fetchTodosQuery(),210+ refreshQuery: fetchTodosQuery,211+ getKey: (todo: Todo) => todo.id,212+ onInsert: async ({ transaction, collection }) => {213+ const { txid } = await api.todos.create(214+ transaction.mutations.map(({ modified }) => modified),215+ )
kevin-dp(GitHub profile, opens in a new tab) approved these changes
- @@ -0,0 +216,21 @@216+ <p>Live updates stopped. Showing the last synced todos.</p>217+ )}218+ <ul>219+ {todos.map((todo) => (220+ <li key={todo.id}>{todo.title}</li>221+ ))}222+ </ul>223+ </>224+ )225+}226+```227+228+Sync begins when the first live query subscribes, unless `startSync` is enabled. The collection becomes ready after the first complete query result arrives. Other views can query the same rows without another sealed query or server round trip.229+230+## Persistence Handlers & Synchronization231+232+Realtime syncs reads. Persist writes through your own backend using `onInsert`, `onUpdate`, and `onDelete`. TanStack DB applies changes optimistically and invokes the matching handler once per transaction, with all of its mutations.233+234+After the backend commits a write, wait for its Postgres transaction ID with `collection.utils.awaitTxId(txid, timeout)`. This keeps the optimistic state until the corresponding synced changes have entered TanStack DB's sync queue.235+236+In `collections.ts`, keep the existing imports, `client`, `fetchTodosQuery`, and `TodosCollection` type. Add the `api` import and error class below, and **replace** the existing `createTodosCollection` function with this writable version. The application API functions send `{ userId, batch }` in one request, pass `signal` to `fetch`, and return `{ txid: string | null }`, with `null` when no rows changed:
thruflo(GitHub profile, opens in a new tab) approved these changes
@@ -0,0 +1,18 @@1+---2+title: Neon Realtime Collection3+---4+5+Neon Realtime collections integrate TanStack DB with [Neon Realtime](https://neon.com/docs/realtime/overview), syncing the results of live SQL queries from Postgres into client-side collections.6+7+## Overview8+9+The `@neon/realtime-tanstack` package, maintained by Neon, allows you to create collections that:10+11+Sync live SQL query results, including joins, aggregates, ordering, and limits12+Apply complete query results and committed change batches atomically13+Support local live queries with filters, sorts, and joins across collections14+Handle optimistic updates with transaction ID matching and automatic rollback on errors15+16+Neon Realtime is currently in beta. Follow the [Neon Realtime quickstart](https://neon.com/docs/realtime/quickstart) to enable it on your branch and configure your application's allowed origins before creating a collection.17+18+ **Version compatibility:** The published `@neon/realtime-tanstack@0.1.1` adapter supports TanStack DB **0.9 only**. It has not been updated for **1.0 RC**. The TanStack DB examples below use 1.0 RC APIs and require a compatible adapter release. For a working 0.9 integration today, follow [Neon's TanStack example](https://neon.com/docs/realtime/examples/tanstack).
Sign in to join this conversation.
⚠️ No Changeset found#
Latest commit: e1cb715cf4b415832de9fb502d66f3306bc5c7f1
Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.
This PR includes no changesets
When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types
Click here to learn what changesets are, and how to add one.
Click here if you're a maintainer who wants to add a changeset to this PR