Generated banner for Neon Realtime
Generated logo for Neon Realtime

Neon Realtime

NeonOfficialPublished by Neon

  • Skill
  • Tool integration
  • Data and AI
  • Apache-2.0
  • No issues found

From the author

Neon Realtime makes any SQL query live. Build realtime, reactive apps and agents on Lakebase Postgres with live SQL queries and reactivity primitives. Use when app UI or agent state must update live from database rows (dashboards, feeds, collaboration, multi-user or multi-device sync), for optimistic mutations, or to replace polling or other realtime sync systems. Triggers include "live query", "subscribe", "sync engine", "useLiveQuery", "TanStack DB", "optimistic updates", "@neon/realtime". For push that doesn't come from database rows (presence, typing, LLM streams), use neon-functions.
— the description by Neon

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Neon Realtime enables developers to create reactive applications and agents by transforming static SQL queries into live, streaming data sources. By utilizing a combination of server-side query sealing and client-side reactivity primitives, it allows UI components and agent states to update automatically as database rows change. This approach eliminates the need for manual polling or complex custom synchronization logic, providing a type-safe, performant way to keep frontends and backend services in sync with the underlying Postgres database.

What it does

  • Converts standard SQL queries into live, reactive data streams.
  • Provides secure query sealing to prevent unauthorized data access or modification.
  • Supports optimistic UI updates to ensure immediate user feedback during data mutations.
  • Integrates with popular ORMs like Drizzle and Kysely for seamless development.
  • Offers React-specific hooks for binding live database state to UI components.
  • Enables efficient synchronization for dashboards, feeds, and multi-user collaboration.

When to use it

  • When building dashboards or feeds that require live data updates.
  • When implementing collaborative features that need multi-user or multi-device synchronization.
  • When you want to replace inefficient polling mechanisms with a push-based sync system.
  • When developing optimistic UI patterns to improve perceived application performance.
  • When building AI agents that need to react to real-time changes in database state.

Advantages

  • Reduces network overhead by replacing polling with WebSocket-based streaming.
  • Simplifies state management by keeping UI in sync with database transactions.
  • Enhances user experience through instant, optimistic UI updates.
  • Maintains security by authorizing and sealing queries on the backend.
  • Works with existing SQL knowledge and familiar ORM workflows.

Usage examples

“How do I make a list of messages in my chat app update in real-time?”
You define a sealed SQL query on your backend that selects messages for a specific channel, then use the useLiveQuery hook in your React frontend to subscribe to that query and automatically update the message list as new rows are inserted.
“How can I implement optimistic updates for a user action?”
You perform the write operation through your backend, return the transaction ID, and use the awaitTxId utility on the client to wait for the database confirmation while immediately updating the local UI state.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/neondatabase/neon-realtime/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip neon-realtime.zip -d .agents/skills

Documentation by Neon

FIRST: Use the parent neon skill for a Neon overview, getting started with Neon, Neon development best practices, and more.

If the neon skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:

neon skills -s neon -y

Neon Realtime

Neon's Realtime makes any SQL query live. Subscribe in realtime to your Lakebase Postgres database. Develop apps and agents with end-to-end reactivity using type-safe live queries and optimistic mutations.

Realtime is new and in beta, so its APIs aren't in your training data. Start from the core pattern below, and read each section's reference file before writing that code.

How It Works

Realtime's layers compose: a live query engine inside Postgres, the Live SQL API (a WebSocket API), lower-level client SDKs (seal(), subscribe()), and reactivity primitives such as useLiveQuery.

  1. In trusted backend code, define a live query (any read-only SQL, including joins, aggregates, ordering and limits), seal it with NEON_REALTIME_SECRET and expose it from an authenticated endpoint or server function. The client can't read or change a sealed query's SQL or parameters.

  2. The client subscribes with the sealed query. It receives the full initial result, then each committed transaction's changes as one batch. Results stay consistent, but delivery of every change event isn't guaranteed.

  3. Writes go through your own API, which returns each write's txid for awaitTxId().

Core Pattern

The guides' chat app, with messages authorized through channel_members. The backend seals the query and returns each write's txid:

import { createRealtime, rawSql } from "@neon/realtime/server"
import { drizzleAdapter } from "@neon/realtime-drizzle"
import { and, desc, eq, getTableColumns, sql } from "drizzle-orm"
import { Hono } from "hono"
import { HTTPException } from "hono/http-exception"
import { requireUser } from "./auth"
import { db } from "./db"
import { channelMembers, messages, type Message } from "./schema"

export const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET!, db: "neondb", adapter: drizzleAdapter() })

// Each selected key must match its column name
export function messagesQuery(userId: string, channelId: number) {
  return db
    .select(getTableColumns(messages)).from(messages)
    .innerJoin(channelMembers, eq(channelMembers.channel_id, messages.channel_id))
    .where(and(eq(channelMembers.user_id, userId), eq(messages.channel_id, channelId)))
    .orderBy(desc(messages.created_at))
    .limit(50)
}

// Or raw SQL
const rawMessagesQuery = (userId: string, channelId: number) => rawSql<Message>(
    `SELECT messages.author_id, messages.body, messages.channel_id, messages.created_at, messages.id FROM messages
     INNER JOIN channel_members ON channel_members.channel_id = messages.channel_id WHERE channel_members.user_id = $1 AND messages.channel_id = $2 ORDER BY messages.created_at DESC LIMIT 50`,
    [userId, channelId]
  )

// The id of the transaction that made the change, read in the write's own RETURNING
const txid = sql<string>`pg_current_xact_id()::text`

const app = new Hono()
  .post("/api/v1/messages/live", async (c) => {
    const user = await requireUser(c)
    const { channelId } = await c.req.json<{ channelId: number }>() // validate input
    return c.json(await realtime.seal({ query: messagesQuery(user.id, channelId) }))
  })
  .post("/api/v1/messages", async (c) => {
    const user = await requireUser(c)
    const { id, channelId, body } = await c.req.json<{ id: string; channelId: number; body: string }>() // validate input
    // One statement. The membership row supplies channel_id and author_id, so only a member's message is inserted.
    // List every column in table order, alias each sql field, and cast untyped params (they resolve to text)
    const [sent] = await db.insert(messages).select(
      db.select({
          id: sql`${id}::uuid`.as("id"), channel_id: channelMembers.channel_id, author_id: channelMembers.user_id,
          body: sql`${body}`.as("body"), created_at: sql`now()`.as("created_at"),
        })
        .from(channelMembers)
        .where(and(eq(channelMembers.channel_id, channelId), eq(channelMembers.user_id, user.id)))
    ).returning({ txid })
    if (!sent) throw new HTTPException(403, { message: "Not a member of this channel" })
    return c.json({ kind: "committed", txid: sent.txid })
  })

The React frontend subscribes and sends optimistic messages:

import { createRealtimeClient, type SealedLiveQuery } from "@neon/realtime/client"
import { drizzleParsers } from "@neon/realtime-drizzle/client"
import { useLiveQuery } from "@neon/realtime-react"
import { startTransition, useCallback, useOptimistic } from "react"
import type { Message } from "../backend/schema"
import { fetchSealedMessages, sendMessage } from "./api"

// One client per app, because subscriptions share its connection. Wrap the app in <RealtimeProvider client={client}>
export const client = createRealtimeClient({ url: import.meta.env.VITE_NEON_REALTIME_URL, parsers: { ...drizzleParsers } })

const NO_MESSAGES: readonly Message[] = []
type Props = { sealedQuery: SealedLiveQuery<Message>; channelId: number; userId: string }

export function Messages({ sealedQuery, channelId, userId }: Props) {
  const refreshQuery = useCallback(() => fetchSealedMessages(channelId), [channelId])
  const { data, status, error, utils } = useLiveQuery(sealedQuery, { refreshQuery })
  // Once the sent message syncs, show only the synced row
  const [messages, addOptimistic] = useOptimistic(data ?? NO_MESSAGES, (current, message: Message) =>
    current.some(({ id }) => id === message.id) ? current : [message, ...current]
  )

  function send(body: string) {
    // The server sets author and timestamp but keeps this id
    const message = { id: crypto.randomUUID(), channel_id: channelId, author_id: userId, body, created_at: new Date() }
    startTransition(async () => {
      addOptimistic(message)
      try {
        const result = await sendMessage(message) // maps channel_id to channelId
        if (result.kind === "committed") await utils.awaitTxId(result.txid, 10_000)
      } catch { /* show "Couldn't confirm the change" */ }
    })
  }

  if (status === "error") return <p role="alert">Live updates stopped: {error.message}</p>
  if (data === undefined) return <p>Loading messages</p>
  return (
    <form action={(form) => send(String(form.get("body")))}>
      <input name="body" required />
      <ul>{messages.map((message) => <li key={message.id}>{message.body}</li>)}</ul>
    </form>
  )
}

Choose the Stack

A live query replaces fetching app data from an API or another sync system. Reuse existing query code, and use the highest layer that fits rather than wiring changes into app state by hand.

UseFor
drizzleAdapter() from @neon/realtime-drizzle, or kyselyAdapter() from @neon/realtime-kyselyQueries written in Drizzle or Kysely
rawSql from @neon/realtime/serverAny other ORM, or none
useLiveQuery from @neon/realtime-reactReact. Binds one sealed query to a component's state
realtimeCollectionOptions from @neon/realtime-tanstackMany views over the same data, or an app on TanStack DB. Oversync one broader query into a collection, then derive local live queries from it
client.subscribe() from @neon/realtime/clientOther frameworks
realtime.subscribe() from @neon/realtime/serverAgents and workers, in trusted backend code

Migrating from Electric: Realtime is a drop-in replacement for Electric's role in your stack. Live SQL queries replace shapes, and realtimeCollectionOptions() replaces electricCollectionOptions().

Setup

  • New app: neon bootstrap my-app --template realtime-react, then neon deploy in my-app.

  • Enable it on the linked branch with neon realtime enable --allowed-origin <app origin>, or declare preview: { realtime: true } in neon.ts (neon config add realtime) and run neon deploy. Child branches inherit it. It's unavailable on Claimable projects until claimed, or outside the supported regions.

  • Tables need a stable replica identity; a primary key is enough. Leave row-level security off on every table a live query reads: Realtime rejects those subscriptions with unsupported query: row security. For per-user data, authorize in the sealed query instead (see below).

  • Environment: neon env pull --service postgres --service realtime writes DATABASE_URL, NEON_REALTIME_URL and NEON_REALTIME_SECRET. Expose only the URL to the browser, under your framework's public prefix (like VITE_). url options take NEON_REALTIME_URL; db takes the database name from DATABASE_URL.

  • Install @neon/realtime and the packages chosen above. Use these SDKs, not the still-evolving WebSocket protocol.

Define and Seal Queries

Read references/queries.md before writing query or sealing code, including Kysely and server functions.

  • Read-only and deterministic. A raw query is a single SELECT with no ; and $1 placeholders. It can't call now() or gen_random_uuid(), so pass such values as parameters, wrapping every value except strings, numbers, booleans, bigints and null in a pgParam helper (pgParam.timestamptz(date)).

  • Authorize in the query. Check the session before sealing, and join through your membership tables so revoked access drops out. Any web framework auth works, including Managed Better Auth, but not RLS yet. See Authorization.

  • A sealed query is a bearer token. Keep it out of URLs, logs and persistent storage, and never fill its parameters from unchecked input.

  • Check a query before wiring it in: neon realtime subscribe "SELECT ..." prints the initial result, then each transaction's changes, until you stop it. With --output json, each change prints a full snapshot. Set debugMode on createRealtime for full database errors (development only).

  • Sealed queries expire. Pass refreshQuery to the bindings or call renew(), sealing the same query and parameters, or the subscription errors. New parameters need a new sealed query and subscription. In Next.js, renew from a Route Handler, because server actions run one at a time.

Subscribe

Read references/reactivity.md before writing React or TanStack DB code. Read references/subscribing.md before subscribing directly with client.subscribe(sealed) (getSnapshot, onChange, onStateChange), or from agents and workers, which add url to createRealtime and await realtime.subscribe(query) to seal in-process.

  • One database per client. The first sealed query binds the connection to its db.

  • Select a stable, unique key for every row and key rows by it, including TanStack DB's getKey: usually the primary key, the grouped columns for aggregates, or the combined keys for joins that repeat a row. Never use rowId, which every rows update invalidates.

  • error is final, even after renew(). Fetch a fresh sealed query and subscribe again, with a new client if the connection failed. Watch onStateChange on direct subscriptions; useLiveQuery() reports errors through status, not by throwing or suspending.

  • When the session changes, leave with a full page load. It drops the Realtime client, any TanStack DbClient and the previous user's rows. The hook retries a failed renewal every second, so stop renewing once one fails as signed out. Check on every renewal and write that the session's user is the one the page was loaded for, or a write from the old page lands in the new user's account. See When the session changes.

Optimistic Writes

Realtime has no write path, so writes keep your backend's usual auth. Read references/mutations.md before writing mutations, for each layer.

  • Return the txid from the write itself: .returning({ txid: sql<string>`pg_current_xact_id()::text` }), in one round trip on any Postgres driver. Write a batch in one statement, so there's one txid. Never open db.transaction() just to select pg_current_xact_id(): that's four round trips holding a pooled connection. When a write genuinely needs several statements, put the txid in the RETURNING of a write that always changes a row.

  • Always pass awaitTxId() a timeout: it keeps waiting through reconnects and renewals, and never settles if the txid doesn't reach the query.

  • A write that changes no rows has no txid, so skip awaitTxId() and let the optimistic state drop.

Server-Side Rendering

Read references/ssr.md before rendering live queries on the server, for Next.js and TanStack Start.

  • Create the client in a useState initializer rather than at module level, render initialData as live rows without a loading state, and never share a TanStack DbClient between requests.

  • Keep row shapes identical on both sides. JSON.stringify turns dates into strings, and int8 and numeric arrive as strings.

More Docs

TaskPage
Beta scope, regions, pricing, FAQ, other systemsOverview
Architecture and consistencyHow it works
A first live queryQuickstart
Every SDK exportTypeScript SDK reference
Full-stack apps with auth and SSRNext.js, TanStack
Live agent workflowsMastra
ORM adaptersDrizzle, Kysely

Files

references/ssr.md

<!-- Generated by scripts/sync-skill-docs.mjs from website@docs/neon-auth-package-rename:bf3595986 (docs/realtime/guides/ssr). Do not edit: change the docs and run npm run sync:docs. sha256:706192b0e9baf22373be7c09fa4e264a0ef62a5fd829043e2fae0691a52da93a -->

Canonical page: https://neon.com/docs/realtime/guides/ssr.md

Summary: Server-render pages that use live queries. Read and seal the same query for each request, send both to the browser, render the initial rows straight away and let the first result bring the page live.

Server-side rendering

Render sealed queries and initial query results on the server.

Contents

  • Return the sealed query and initial results

  • Send both to the browser

  • Render the initial rows straight away

  • Open the connection in the browser

  • Keep row shapes identical

  • Renew from the server

  • When the session changes

  • With TanStack DB

    • Create a DbClient per router

    • Define the collection

    • Seed the collection in a loader

  • Keep secrets on the server

  • Examples

Server-side rendering (SSR) lets a page arrive with its rows already in the HTML, then subscribe to ongoing changes as soon as it hydrates.

Realtime supports SSR, including with Next.js and TanStack Start.

Return the sealed query and initial results

The pattern is to build the live query once and then use it twice in the same request:

  1. run the query to get the initial results

  2. seal the query so it can be subscribed to safely on the frontend

Running and sealing the query are both async, so do them in parallel using Promise.all:

import type { SealedLiveQuery } from "@neon/realtime/server"

import { messagesQuery } from "./queries"
import { realtime } from "./realtime"
import type { Message } from "./schema"

export interface MessagesPageData {
  initialData: Message[];
  sealedQuery: SealedLiveQuery<Message>;
}

// Call this per request. The result belongs to one user and is short-lived.
export async function loadMessagesPage(userId: string, channelId: number): Promise<MessagesPageData> {
  const query = messagesQuery(userId, channelId)

  const [initialData, sealedQuery] = await Promise.all([query, realtime.seal({ query })])

  return { initialData, sealedQuery }
}

messagesQuery() and realtime are the ones from defining queries. Your Server Component or server function calls loadMessagesPage() with the user's id from the verified auth session.

Send both to the browser

Both values are serializable, so they go into the hydration payload with the rest of the page's props or loader data. The framework serializes them into the HTML it sends, and the browser picks them up when it hydrates.

For example with Next.js, call loadMessagesPage() from a Server Component and pass the results to a Client Component as props. auth is the Managed Better Auth server instance in lib/auth/server.ts, set up as in the Managed Better Auth Next.js quick start. The page must render per request, because auth.getSession() reads cookies, so it sets force-dynamic. If your app enables cacheComponents, remove the dynamic export and read the session inside a <Suspense> boundary instead.

import { notFound, redirect } from "next/navigation"

import { loadMessagesPage } from "../../../backend/messages-page"
import { auth } from "../../../lib/auth/server"
import { ChannelMessages } from "./ChannelMessages"

export const dynamic = "force-dynamic"

type Props = {
  params: Promise<{ channelId: string }>
}

export default async function MessagesPage({ params }: Props) {
  const { data: session } = await auth.getSession()

  if (!session?.user) {
    redirect("/auth/sign-in")
  }

  const channelId = Number((await params).channelId)

  if (!Number.isInteger(channelId)) {
    notFound()
  }

  const { initialData, sealedQuery } = await loadMessagesPage(session.user.id, channelId)

  return (
    <ChannelMessages
      key={sealedQuery.queryFingerprint}
      channelId={channelId}
      initialData={initialData}
      sealedQuery={sealedQuery}
    />
  )
}

ChannelMessages is a Client Component. It builds refreshQuery, which renews the sealed query through a Route Handler, and renders HydratedMessages:

"use client"

import { useCallback } from "react"
import type { SealedLiveQuery } from "@neon/realtime/client"

import type { Message } from "../../../backend/schema"
import { HydratedMessages } from "../../../frontend/HydratedMessages"

interface Props {
  channelId: number;
  initialData: Message[];
  sealedQuery: SealedLiveQuery<Message>;
}

export function ChannelMessages({ channelId, initialData, sealedQuery }: Props) {
  // Renewals must be for the same query, so renew with the same channel
  const refreshQuery = useCallback(async () => {
    const res = await fetch(`/api/messages/${channelId}/live`, { method: "POST" })

    if (!res.ok) {
      throw new Error(`Could not fetch the sealed query (${res.status})`)
    }

    return (await res.json()) as SealedLiveQuery<Message>
  }, [channelId])

  return <HydratedMessages sealedQuery={sealedQuery} refreshQuery={refreshQuery} initialData={initialData} />
}

The Route Handler takes the user from the session cookie, not from the request, and validates channelId, because the browser controls the URL. Then it seals the same messagesQuery() as the page:

import { messagesQuery } from "../../../../../backend/queries"
import { realtime } from "../../../../../backend/realtime"
import { auth } from "../../../../../lib/auth/server"

type Context = {
  params: Promise<{ channelId: string }>
}

export async function POST(_request: Request, { params }: Context) {
  const { data: session } = await auth.getSession()

  if (!session?.user) {
    return Response.json({ error: "Unauthorized" }, { status: 401 })
  }

  const channelId = Number((await params).channelId)

  if (!Number.isInteger(channelId)) {
    return Response.json({ error: "channelId must be an integer" }, { status: 400 })
  }

  const sealedQuery = await realtime.seal({ query: messagesQuery(session.user.id, channelId) })

  return Response.json(sealedQuery, { headers: { "Cache-Control": "no-store" } })
}

A server re-render, for example from router.refresh() or revalidatePath(), sends a new object for the same query. useLiveQuery() restarts on each new object, which rejects pending awaitTxId() calls. So HydratedMessages keeps the first sealed query, and renewals go through refreshQuery. Callers key it on queryFingerprint, so another channel or user remounts it.

Or with TanStack Start, create server functions for the loader and the renewal. During SSR, a route loader needs the session from the request's cookies on the server. The official Managed Better Auth adapter for TanStack Start isn't out yet, so set up the session yourself. requireUser reads the cookie during SSR and for calls from the browser:

<details>

<summary>Read the Managed Better Auth session in TanStack Start</summary>

This setup is built on the beta Managed Better Auth server toolkit, @neon/auth/server. Swap in the official adapter when it ships.

Create the auth server. It reads and sets the session cookies through TanStack Start's request helpers:

import { createAuthServer, extractNeonAuthCookies } from "@neon/auth/server"
import { getRequest, setCookie } from "@tanstack/react-start/server"

export const authConfig = {
  baseUrl: process.env.NEON_AUTH_BASE_URL!,
  cookieSecret: process.env.NEON_AUTH_COOKIE_SECRET! // 32+ characters
}

export const auth = createAuthServer({
  ...authConfig,
  context: () => {
    const request = getRequest()

    return {
      getCookies: () => extractNeonAuthCookies(request.headers),
      setCookie,
      getHeader: (name) => request.headers.get(name),
      getOrigin: () => request.headers.get("origin") ?? new URL(request.url).origin,
      getFramework: () => "tanstack-start"
    }
  }
})

NEON_AUTH_COOKIE_SECRET signs the session cookie and must be at least 32 characters. Generate it once:

printf '\nNEON_AUTH_COOKIE_SECRET=%s\n' "$(openssl rand -base64 32)" >> .env.local

Mount the Managed Better Auth proxy at /api/auth, so the session cookie lives on your app's origin:

import { handleAuthProxyRequest } from "@neon/auth/server"
import { createFileRoute } from "@tanstack/react-router"

import { authConfig } from "../../../backend/auth"

export const Route = createFileRoute("/api/auth/$")({
  server: {
    handlers: {
      ANY: ({ request, params }) =>
        handleAuthProxyRequest({ request, path: params._splat ?? "", ...authConfig })
    }
  }
})

requireUser only has a server half. It puts the user's id on context, and throws without a session, so it guards your data. getSessionUser reads the session without throwing, for route guards:

import { createMiddleware, createServerFn } from "@tanstack/react-start"
import { setResponseHeader } from "@tanstack/react-start/server"

import { auth } from "./backend/auth"

export const requireUser = createMiddleware({ type: "function" }).server(async ({ next }) => {
  const { data } = await auth.getSession()

  if (!data?.user) {
    throw new Error("Unauthorized")
  }

  return next({ context: { user: { id: data.user.id } } })
})

export const getSessionUser = createServerFn({ method: "GET" }).handler(async () => {
  setResponseHeader("Cache-Control", "private, no-store")
  const { data } = await auth.getSession()

  return data?.user ? { id: data.user.id } : null
})

Point the auth client at the proxy. An empty URL makes it use /api/auth on the page's origin:

import { createAuthClient } from "@neon/auth"

export const authClient = createAuthClient("") // same origin: /api/auth

</details>

The root route puts the user on the router context for every navigation. During SSR, getSessionUser runs in the same process, with the request's cookies. The route's headers keep every page out of shared caches:

import { createRootRoute } from "@tanstack/react-router"

import { getSessionUser } from "../session-middleware"

export const Route = createRootRoute({
  beforeLoad: async () => ({ user: await getSessionUser() }),
  // Pages carry one user's rows and sealed query, so no shared cache may store them
  headers: () => ({ "Cache-Control": "private, no-store", Vary: "Cookie" })
  // … shell unchanged
})

The redirects below go to the sign-in route from the Managed Better Auth TanStack Router quick start, src/routes/auth.$pathname.tsx.

Both server functions use requireUser, so they take the user from the session and only channelId from the request. The route's beforeLoad sends signed-out visitors to sign-in before the loader runs. The router reuses the component when only $channelId changes, so the route keys HydratedMessages on the query's fingerprint:

import { useCallback } from "react"
import { createFileRoute, redirect } from "@tanstack/react-router"
import { createServerFn } from "@tanstack/react-start"

import { loadMessagesPage } from "../backend/messages-page"
import { messagesQuery } from "../backend/queries"
import { realtime } from "../backend/realtime"
import { HydratedMessages } from "../frontend/HydratedMessages"
import { requireUser } from "../session-middleware"

function validateChannel(data: { channelId: number }) {
  if (!Number.isInteger(data.channelId)) {
    throw new Error("channelId must be an integer")
  }

  return data
}

const loadMessages = createServerFn({ method: "POST" })
  .middleware([requireUser])
  .validator(validateChannel)
  .handler(({ data, context }) => loadMessagesPage(context.user.id, data.channelId))

const sealMessages = createServerFn({ method: "POST" })
  .middleware([requireUser])
  .validator(validateChannel)
  .handler(({ data, context }) =>
    realtime.seal({ query: messagesQuery(context.user.id, data.channelId) })
  )

export const Route = createFileRoute("/channels/$channelId")({
  beforeLoad: ({ context }) => {
    if (!context.user) {
      throw redirect({ to: "/auth/$pathname", params: { pathname: "sign-in" } })
    }
  },
  loader: ({ params }) => loadMessages({ data: { channelId: Number(params.channelId) } }),
  component: MessagesRoute
})

function MessagesRoute() {
  const { channelId } = Route.useParams()
  const { initialData, sealedQuery } = Route.useLoaderData()

  // Renewals must be for the same query, so renew with the same channel
  const refreshQuery = useCallback(
    () => sealMessages({ data: { channelId: Number(channelId) } }),
    [channelId]
  )

  return (
    <HydratedMessages
      key={sealedQuery.queryFingerprint}
      initialData={initialData}
      sealedQuery={sealedQuery}
      refreshQuery={refreshQuery}
    />
  )
}

Important: The sealed query is in your HTML

Anyone with the page source holds the sealed query until it expires, because sealed queries are bearer tokens. Serve the page over HTTPS, keep it out of shared caches, and keep the sealed query out of URLs and logs.

Render the initial rows straight away

Pass the initial rows to useLiveQuery() as initialData. The hook renders them immediately with the status connecting. When the subscription's first result arrives, it replaces them atomically and the status becomes live. Any change committed between the server read and the subscription is in that result, so nothing falls into the gap.

The initial rows are real rows. Render them as you would live ones, without a spinner or a loading state, while the status is connecting. HydratedMessages shows the server's rows straight away and swaps in the live rows when the first result arrives:

"use client"

import { useState } from "react"
import { useLiveQuery } from "@neon/realtime-react"
import type { SealedLiveQuery } from "@neon/realtime/client"

import type { Message } from "../backend/schema"
import { LocalTime } from "./LocalTime"

interface HydratedMessagesProps {
  sealedQuery: SealedLiveQuery<Message>;
  refreshQuery: () => Promise<SealedLiveQuery<Message>>;
  initialData: Message[];
}

export function HydratedMessages({ sealedQuery, refreshQuery, initialData }: HydratedMessagesProps) {
  const [query] = useState(sealedQuery) // renewals go through refreshQuery
  const { data, error } = useLiveQuery(query, { refreshQuery, initialData })

  return (
    <>
      {error && <p role="alert">{error.message}</p>}
      <ul>
        {(data ?? initialData).map((message) => (
          <li key={message.id}>
            <LocalTime date={message.created_at} />
            <p>{message.body}</p>
          </li>
        ))}
      </ul>
    </>
  )
}

The component takes refreshQuery as a prop, so it works with whichever renewal path your framework uses. Renew from the server covers the options. The reactivity guide covers the hook itself and defines LocalTime.

Open the connection in the browser

The server render doesn't open a WebSocket. On the server, the hook renders from its initial rows and never subscribes. In the browser, it renders the same rows while React hydrates, so the HTML matches, and subscribes once hydration is done.

So create the client once, inside the React tree, in a useState initializer. It runs once per mounted app, and the client it creates during the server render never connects, because nothing subscribes there:

Next.js

"use client"

import { useState, type ReactNode } from "react"
import { createRealtimeClient } from "@neon/realtime/client"
import { drizzleParsers } from "@neon/realtime-drizzle/client"
import { RealtimeProvider } from "@neon/realtime-react"

export function RealtimeRoot({ children }: { children: ReactNode }) {
  const [client] = useState(() =>
    createRealtimeClient({
      url: process.env.NEXT_PUBLIC_NEON_REALTIME_URL!,
      parsers: { ...drizzleParsers }
    })
  )

  return <RealtimeProvider client={client}>{children}</RealtimeProvider>
}

TanStack Start

"use client"

import { useState, type ReactNode } from "react"
import { createRealtimeClient } from "@neon/realtime/client"
import { drizzleParsers } from "@neon/realtime-drizzle/client"
import { RealtimeProvider } from "@neon/realtime-react"

export function RealtimeRoot({ children }: { children: ReactNode }) {
  const [client] = useState(() =>
    createRealtimeClient({
      url: import.meta.env.VITE_NEON_REALTIME_URL,
      parsers: { ...drizzleParsers }
    })
  )

  return <RealtimeProvider client={client}>{children}</RealtimeProvider>
}

With Next.js, add the browser's copy of the Realtime URL. Next.js expands $VAR in env files, so it follows neon env pull:

echo 'NEXT_PUBLIC_NEON_REALTIME_URL=$NEON_REALTIME_URL' >> .env.local

With TanStack Start, use the VITE_NEON_REALTIME_URL line from the setup.

The subscribing guide creates the client at module level in frontend/client.ts, which suits a single-page app. In a server-rendered app, create it inside the React tree instead, which keeps browser-only setup out of module scope. Keep the client stable, too. useLiveQuery() subscribes per client and sealed query, so a new client on every render means a new subscription on every render.

Render RealtimeRoot around everything that calls useLiveQuery(), for example in your root layout. RealtimeRoot, ChannelMessages and HydratedMessages start with "use client" so that Next.js renders them as Client Components. TanStack Start ignores the directive.

Keep row shapes identical

The initial rows and the live rows have to have the same shape. If they don't, the page renders one shape until the first result and another after it.

In the running example, created_at is a Date on both sides: Drizzle reads timestamptz columns as Date objects, and so does the Realtime client. The Realtime clients on this page spread drizzleParsers, so the live rows match Drizzle's types for other columns too. The subscribing guide explains what the parsers change. The hydration payload has to keep it that way. React Server Component props and TanStack Start's serializer both preserve Date values. Plain JSON.stringify turns them into strings, so if your payload goes through it, revive the dates in the browser or keep your row types JSON-safe.

Watch numeric types too: int8 and numeric columns arrive as strings on the live side, so read them as strings on the server.

Formatted output has to match too, so format dates and numbers for the user's locale after hydration, as LocalTime in the reactivity guide does.

Renew from the server

The sealed query in the payload expires, so pass refreshQuery, and the hook renews the sealed query with the same timing as in the reactivity guide. If the page hydrates late, for example in a tab restored after a few minutes, the sealed query may already have expired, and the hook renews it straight away.

The renewal runs in the browser, so it goes through something that authenticates the user, like the Route Handler or server function above. It has to seal the same query with the same parameters, because a different fingerprint is rejected. Building both from messagesQuery() keeps them in step.

When the session changes

A page can outlive its session. The user signs out in another tab, or another tab signs in as someone else, and the page still holds the first user's sealed query and rows.

Stop renewing once a renewal fails as signed out, and leave the page. The hook retries a failed renewal every second without limit, and once the sealed query expires the status stays stale.

Check on every renewal and write that the session's user is the one the page was loaded for. Have the page send its user id, and treat a mismatch as signed out, with the same 401 as no session. Otherwise a write from the old page lands in the new user's account.

Leave with a full page load. It drops the previous user's Realtime client, collections and optimistic rows. Then the page's redirect sends a signed-out visitor to sign-in, and a different user gets their own rows. With Next.js, pass session.user.id to ChannelMessages as userId, and have the Route Handler return its 401 when the body's userId isn't session.user.id:

// A full page load resets this
let signedOut = false

export function ChannelMessages({ channelId, userId, initialData, sealedQuery }: Props) {
  const refreshQuery = useCallback(async () => {
    if (signedOut) {
      throw new Error("Signed out")
    }

    // The page's user, so the Route Handler can refuse anyone else's session
    const res = await fetch(`/api/messages/${channelId}/live`, {
      method: "POST",
      body: JSON.stringify({ userId })
    })

    if (res.status === 401) {
      signedOut = true // the hook retries every second, so stop calling the server
      window.location.reload()
      throw new Error("Signed out")
    }

    // … check res.ok and return the sealed query, as above
  }, [channelId, userId])

  // … render HydratedMessages, as above
}

With TanStack Start, have the server functions also take a userId, and make requireUser throw when it isn't the session's user. Leave the same way when a write fails as signed out.

Make sign-in and sign-out full page loads too. With the Managed Better Auth UI components, have the provider's onSessionChange call window.location.assign("/") and return a promise that never settles, so the components don't also navigate in the client.

With TanStack DB

With TanStack DB, the collection carries the initial rows instead of the hook's initialData:

  1. a route loader reads and seals the inbox and seeds the collection in the router's DbClient

  2. routerWithDbClient() carries the seeded rows to the browser

  3. the collection subscribes in the browser, and the first result takes over from the seeded rows

The code below does this with TanStack Start. It syncs the inbox from the reactivity guide into one collection and shows one channel from it. As well as the packages from that guide, it uses TanStack's router integration:

npm install @tanstack/react-router-with-db
Create a DbClient per router

TanStack Start calls getRouter() once per request on the server and once per page load in the browser, so a DbClient created with the router belongs to one request or one page load. Create the Realtime client next to it and pass it to the DbClient as a dependency, so collections can read it. The server-side Realtime client never connects, because nothing subscribes there. routerWithDbClient() wraps the app in DbProvider, snapshots the collections that loaders seeded on the server into the HTML, and restores them in the browser before the first render:

import { DbClient } from "@tanstack/react-db"
import { createRouter } from "@tanstack/react-router"
import { routerWithDbClient } from "@tanstack/react-router-with-db"
import { createRealtimeClient } from "@neon/realtime/client"
import { drizzleParsers } from "@neon/realtime-drizzle/client"

import { routeTree } from "./routeTree.gen"

export function getRouter() {
  // Collections read it with db.requireDependency("realtime"). Nothing subscribes on the server, so it never connects there
  const realtime = createRealtimeClient({
    url: import.meta.env.VITE_NEON_REALTIME_URL,
    parsers: { ...drizzleParsers }
  })
  const dbClient = new DbClient({ realtime })
  const router = createRouter({ routeTree, context: { dbClient } })

  return routerWithDbClient(router, dbClient)
}

routerWithDbClient() requires dbClient in the router's context type, so create the root route from Send both to the browser with createRootRouteWithContext<{ dbClient: DbClient }>() instead of createRootRoute(), and keep its beforeLoad and headers. If the app also uses useLiveQuery() from @neon/realtime-react, pass the same Realtime client to RealtimeProvider. Get it with useDbClient().requireDependency<RealtimeClient>("realtime").

Define the collection

Define the collection as a descriptor with the two-argument collectionOptions(id, factory) around realtimeCollectionOptions(), and give it a stable id. Each DbClient runs the factory once, to create its own instance of the collection. Unlike createMessagesCollection() in the reactivity guide, it doesn't take a Realtime client: the factory reads the one from its DbClient. The descriptor is cheap to build, so the loader and the channel page each build it, and the id resolves both to the same collection:

import { collectionOptions } from "@tanstack/react-db"
import { realtimeCollectionOptions } from "@neon/realtime-tanstack"
import type { RealtimeClient, SealedLiveQuery } from "@neon/realtime/client"

import type { Message } from "./backend/schema"
import { sealInbox } from "./server-functions"

export function messagesCollection(sealedQuery: SealedLiveQuery<Message>) {
  return collectionOptions("messages", (db) =>
    realtimeCollectionOptions({
      id: "messages",
      client: db.requireDependency<RealtimeClient>("realtime"),
      query: sealedQuery,
      refreshQuery: () => sealInbox(),
      getKey: (message) => message.id,
      gcTime: 0 // never collect it while the page is open: a rebuilt collection would reuse an expired sealed query
    })
  )
}

refreshQuery calls a server function that seals the same inboxQuery() for the user in the session:

import { createServerFn } from "@tanstack/react-start"

import { inboxQuery } from "./backend/queries"
import { realtime } from "./backend/realtime"
import { requireUser } from "./session-middleware"

export const sealInbox = createServerFn({ method: "POST" })
  .middleware([requireUser])
  .handler(({ context }) => realtime.seal({ query: inboxQuery(context.user.id) }))
Seed the collection in a loader

A layout route, src/routes/channels.tsx, loads the inbox for every channel page. Its loader calls a server function that reads and seals the inbox. Then it seeds the collection in the router's DbClient, passing the rows to dbClient.collection() as initialData, which is TanStack DB's option for seeding a collection in one DbClient. It returns only the sealed query. Its beforeLoad sends signed-out visitors to sign-in, so the channel pages, which render in its outlet, don't need to:

import { createFileRoute, redirect } from "@tanstack/react-router"
import { createServerFn } from "@tanstack/react-start"

import { inboxQuery } from "../backend/queries"
import { realtime } from "../backend/realtime"
import { messagesCollection } from "../collections"
import { requireUser } from "../session-middleware"

const loadInbox = createServerFn({ method: "POST" })
  .middleware([requireUser])
  .handler(async ({ context }) => {
    const query = inboxQuery(context.user.id)
    const [initialData, sealedQuery] = await Promise.all([query, realtime.seal({ query })])

    return { initialData, sealedQuery }
  })

export const Route = createFileRoute("/channels")({
  staleTime: Infinity,
  beforeLoad: ({ context }) => {
    if (!context.user) {
      throw redirect({ to: "/auth/$pathname", params: { pathname: "sign-in" } })
    }
  },
  loader: async ({ context }) => {
    const { initialData, sealedQuery } = await loadInbox()
    context.dbClient.collection(messagesCollection(sealedQuery), { initialData }) // a no-op if it already exists

    return { sealedQuery }
  }
})

The layout's loader runs once, because staleTime: Infinity keeps its data fresh, so switching channels makes no server round trip. On the first load, the loader and the channel page both run on the server, so the HTML has the rows. If the loader runs again in the browser, the collection already exists, so seeding it again does nothing and the live rows stay.

One collection id is enough, because each DbClient belongs to one request or one page load, and the full page load when the session changes drops it.

The channel route builds the same descriptor from the layout's sealed query, so it gets the collection the loader seeded. It queries the collection with TanStack's useLiveQuery(), under the same alias as in the reactivity guide:

import { eq, useLiveQuery as useCollectionQuery } from "@tanstack/react-db"
import { createFileRoute, getRouteApi } from "@tanstack/react-router"

import { messagesCollection } from "../collections"

const channels = getRouteApi("/channels")

export const Route = createFileRoute("/channels/$channelId")({
  component: ChannelRoute
})

function ChannelRoute() {
  const { channelId } = Route.useParams()
  const messages = messagesCollection(channels.useLoaderData().sealedQuery) // same id, so the seeded collection

  const { data, isError } = useCollectionQuery({
    query: (q) =>
      q
        .from({ message: messages })
        .where(({ message }) => eq(message.channel_id, Number(channelId)))
        .orderBy(({ message }) => message.created_at, "desc")
  })

  if (isError) {
    return <p role="alert">Couldn't sync messages</p>
  }

  return (
    <ul>
      {data.map((message) => (
        <li key={message.id}>{message.body}</li>
      ))}
    </ul>
  )
}

Render data straight away, without waiting for isReady. The seeded rows are there for the first render, but the collection only becomes ready when the first result arrives.

Keep secrets on the server

In a server-rendered app, server and browser code live side by side, so it's easy to import a module on the wrong side. Import backend/realtime.ts and backend/db.ts only from server code: Server Components, server functions and TanStack Start server function handlers. A TanStack Start route loader also runs in the browser on client-side navigation, so it has to call a server function rather than import backend/ modules.

Mark those modules as server-only, so a client import fails the build. In Next.js, add import "server-only" to backend/realtime.ts and backend/db.ts. In TanStack Start, add import "@tanstack/react-start/server-only" to them, or name the files *.server.ts. The queries guide explains why you keep your Realtime secret on the server.

Examples

The examples put these principles into framework code. The Next.js example splits the page into a Server Component that reads and seals and a Client Component that subscribes. Instead of force-dynamic, it calls connection() in that Server Component and renders it inside <Suspense>, so the rest of the page renders at once and the list streams in. The TanStack example seeds the router's TanStack DB client in a route loader.

  • Next.js: Read and seal in a Server Component, then subscribe in a Client Component.

  • TanStack: Seed the router's TanStack DB client in a route loader.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs network access

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Neon
Publisher
Neon (Official)
Source
neondatabase/agent-skills · skills/neon-realtime · commit 2b0e2b6
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
neondatabase/agent-skills

AutoGineer is not affiliated with or endorsed by Neon.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download neon-realtime.zip