AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

neon-realtime

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.

Original source
neondatabase
License
Apache-2.0
Pinned revision
d3da7cb5436edbb2bc8c00747fafd31ddf0644f4

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read neondatabase--neon-realtime at revision d3da7cb5436edbb2bc8c00747fafd31ddf0644f4, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 6

references/ssr.md

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

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:

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

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