references/ssr.md · 24000
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.