> This page location: Realtime > Guides > Server-side rendering
> Full Neon documentation index: https://neon.com/docs/llms.txt

> 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.

[Server-side rendering (SSR)](https://developer.mozilla.org/en-US/docs/Glossary/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](../examples/nextjs) and [TanStack Start](../examples/tanstack).

## Return the sealed query and initial results

The pattern is to [build the live query](./queries#defining-live-queries) once and then use it twice in the same request:

1. run the query to get the initial results
2. [seal the query](./queries#sealing-queries) 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`:

```ts filename="backend/messages-page.ts"
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](./queries#using-a-query-builder-or-orm). Your Server Component or server function calls `loadMessagesPage()` with the user's id from the [verified auth session](./queries#authorization).

## 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](../examples/nextjs), 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](https://neon.com/docs/auth/quick-start/nextjs-api-only). The page must render per request, because `auth.getSession()` [reads cookies](https://neon.com/docs/auth/troubleshooting#missing-force-dynamic-on-server-components), so it sets `force-dynamic`. If your app enables `cacheComponents`, remove the `dynamic` export and read the session inside a `<Suspense>` boundary instead.

```tsx filename="app/channels/[channelId]/page.tsx"
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](https://neon.com/docs/realtime/guides/ssr#renew-from-the-server) through a Route Handler, and renders [`HydratedMessages`](https://neon.com/docs/realtime/guides/ssr#render-the-initial-rows-straight-away):

```tsx filename="app/channels/[channelId]/ChannelMessages.tsx"
"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:

```ts filename="app/api/messages/[channelId]/live/route.ts"
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](../examples/tanstack), [create server functions](https://tanstack.com/start/latest/docs/framework/react/guide/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, `@neondatabase/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:

```ts filename="src/backend/auth.ts"
import { createAuthServer, extractNeonAuthCookies } from "@neondatabase/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:

```bash filename="Terminal"
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:

```ts filename="src/routes/api/auth/$.ts"
import { handleAuthProxyRequest } from "@neondatabase/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:

```ts filename="src/session-middleware.ts"
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:

```ts filename="src/frontend/auth.ts"
import { createAuthClient } from "@neondatabase/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:

```tsx filename="src/routes/__root.tsx"
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](https://neon.com/docs/auth/quick-start/tanstack-router), `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:

```tsx filename="src/routes/channels.$channelId.tsx"
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](./queries#sealing-queries). 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()`](./reactivity) 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:

```tsx filename="frontend/HydratedMessages.tsx"
"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](https://neon.com/docs/realtime/guides/ssr#renew-from-the-server) covers the options. The [reactivity guide](./reactivity#uselivequery) 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**

```tsx filename="frontend/RealtimeRoot.tsx"
"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**

```tsx filename="frontend/RealtimeRoot.tsx"
"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`:

```bash filename="Terminal"
echo 'NEXT_PUBLIC_NEON_REALTIME_URL=$NEON_REALTIME_URL' >> .env.local
```

With TanStack Start, use the `VITE_NEON_REALTIME_URL` line from the [setup](./queries#setup).

The [subscribing guide](./subscribing#subscribe-to-the-sealed-query) 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](./subscribing#subscribe-to-the-sealed-query) 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](./subscribing#subscribe-to-the-sealed-query) 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](./reactivity#refreshquery). 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`:

```tsx filename="app/channels/[channelId]/ChannelMessages.tsx"
// 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](./reactivity#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](./reactivity#seal-a-broader-query) into one collection and shows one channel from it. As well as the packages from that guide, it uses TanStack's router integration:

```bash filename="Terminal"
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:

```tsx filename="src/router.tsx"
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](https://neon.com/docs/realtime/guides/ssr#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()`](../sdks/typescript#tanstack-db-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:

```ts filename="src/collections.ts"
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:

```ts filename="src/server-functions.ts"
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:

```tsx filename="src/routes/channels.tsx"
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](https://neon.com/docs/realtime/guides/ssr#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:

```tsx filename="src/routes/channels.$channelId.tsx"
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](./queries#sealing-queries).

## 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](https://neon.com/docs/realtime/examples/nextjs): Read and seal in a Server Component, then subscribe in a Client Component.
- [TanStack](https://neon.com/docs/realtime/examples/tanstack): Seed the router's TanStack DB client in a route loader.

---

## Related docs (Guides)

- [Defining queries](https://neon.com/docs/realtime/guides/queries)
- [Subscribing to queries](https://neon.com/docs/realtime/guides/subscribing)
- [Client-side reactivity](https://neon.com/docs/realtime/guides/reactivity)
- [Optimistic mutations](https://neon.com/docs/realtime/guides/mutations)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/docs/realtime/guides/ssr"}` to https://feedback.neon.tech/ (no auth required).
