<html lang="en">
<head></head>
<body>

<form id="mainForm" method="post" action="https://stackblitz.com/run" target="_self">
<input type="hidden" name="project[files][CHANGELOG.md]" value="# @tanstack/db-example-react-start-ssr-e2e

## 0.0.1

### Patch Changes

- Updated dependencies [[`4b9e8cd`](https://github.com/TanStack/db/commit/4b9e8cdf79551734cf526e6fa4bbdba42ec94575)]:
  - @tanstack/react-db@0.3.0
  - @tanstack/react-router-with-db@0.1.0
">
<input type="hidden" name="project[files][README.md]" value="# TanStack DB Start SSR Demo

This example is a minimal TanStack Start app that demonstrates TanStack DB SSR
with collection-row hydration.

It verifies five things:

- server HTML contains rows loaded through a request-scoped `DbClient`
- the browser hydrates those rows into a client `DbClient`
- fresh adapter sync replaces a stale hydrated row with the same key
- an incremental collection chunk updates an existing live query
- critical collection rows hydrate while a query discovered later in the same
  render streams through a Suspense boundary

Live demo: https://tanstack-db-ssr-demo.netlify.app/ssr-db

## Run Locally

```sh
pnpm --filter @tanstack/db build
pnpm --filter @tanstack/react-db build
pnpm --filter @tanstack/db-example-react-start-ssr-e2e dev
```

Open `/ssr-db` for holistic and incremental hydration, or `/ssr-db-stream` for
render-time Suspense streaming.

## Run E2E

```sh
pnpm --filter @tanstack/db-example-react-start-ssr-e2e test:e2e
```

The Playwright tests cover raw SSR HTML, browser hydration, fresh-sync
reconciliation, incremental collection hydration, and critical hydration plus a
render-time query in the same request. The streaming route shows its Suspense
fallback before the streamed server rows arrive.

## Deploy Demo

The demo requires an SSR-capable host for TanStack Start.

Netlify deployment is configured through `netlify.toml` and
`netlify/functions/server.mjs`. Deploy with:

```sh
cd examples/react/start-ssr-e2e
netlify deploy --prod --site-name tanstack-db-ssr-demo --team tanstack
```

After deployment, verify the live URL with:

```sh
PLAYWRIGHT_BASE_URL=https://your-demo-url pnpm --filter @tanstack/db-example-react-start-ssr-e2e test:e2e:hosted
```
">
<input type="hidden" name="project[files][netlify.toml]" value="[build]
command = &quot;pnpm build&quot;
publish = &quot;dist/client&quot;
functions = &quot;netlify/functions&quot;

[functions]
node_bundler = &quot;esbuild&quot;
included_files = [&quot;dist/server/**&quot;]
">
<input type="hidden" name="project[files][package.json]" value="{
  &quot;name&quot;: &quot;@tanstack/db-example-react-start-ssr-e2e&quot;,
  &quot;private&quot;: true,
  &quot;version&quot;: &quot;0.0.1&quot;,
  &quot;type&quot;: &quot;module&quot;,
  &quot;scripts&quot;: {
    &quot;build&quot;: &quot;vite build&quot;,
    &quot;dev&quot;: &quot;vite dev&quot;,
    &quot;test:e2e&quot;: &quot;pnpm --filter @tanstack/db build &amp;&amp; pnpm --filter @tanstack/react-db build &amp;&amp; pnpm --filter @tanstack/react-router-with-db build &amp;&amp; playwright test&quot;,
    &quot;test:e2e:hosted&quot;: &quot;playwright test&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@tanstack/react-db&quot;: &quot;https://pkg.pr.new/TanStack/db/@tanstack/react-db@97e5c64&quot;,
    &quot;@tanstack/react-router&quot;: &quot;^1.159.5&quot;,
    &quot;@tanstack/react-router-with-db&quot;: &quot;https://pkg.pr.new/TanStack/db/@tanstack/react-router-with-db@97e5c64&quot;,
    &quot;@tanstack/react-start&quot;: &quot;^1.159.5&quot;,
    &quot;react&quot;: &quot;^19.2.4&quot;,
    &quot;react-dom&quot;: &quot;^19.2.4&quot;,
    &quot;vite-tsconfig-paths&quot;: &quot;^5.1.4&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@playwright/test&quot;: &quot;^1.60.0&quot;,
    &quot;@types/node&quot;: &quot;^25.2.2&quot;,
    &quot;@types/react&quot;: &quot;^19.2.13&quot;,
    &quot;@types/react-dom&quot;: &quot;^19.2.3&quot;,
    &quot;@vitejs/plugin-react&quot;: &quot;^5.1.3&quot;,
    &quot;typescript&quot;: &quot;^5.9.2&quot;,
    &quot;vite&quot;: &quot;^7.3.0&quot;
  }
}">
<input type="hidden" name="project[files][playwright.config.ts]" value="import { defineConfig, devices } from &#39;@playwright/test&#39;

const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:4175`
const shouldStartWebServer = process.env.PLAYWRIGHT_BASE_URL === undefined

export default defineConfig({
  testDir: `./e2e`,
  timeout: 30000,
  expect: {
    timeout: 10000,
  },
  fullyParallel: false,
  use: {
    baseURL,
    trace: `on-first-retry`,
  },
  webServer: shouldStartWebServer
    ? {
        command: `pnpm dev --host 127.0.0.1 --port 4175`,
        reuseExistingServer: !process.env.CI,
        timeout: 120000,
        url: baseURL,
      }
    : undefined,
  projects: [
    {
      name: `chromium`,
      use: { ...devices[`Desktop Chrome`] },
    },
  ],
})
">
<input type="hidden" name="project[files][tsconfig.json]" value="{
  &quot;extends&quot;: &quot;../../../tsconfig.json&quot;,
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;.&quot;,
    &quot;module&quot;: &quot;ES2022&quot;,
    &quot;moduleResolution&quot;: &quot;bundler&quot;,
    &quot;jsx&quot;: &quot;react-jsx&quot;,
    &quot;paths&quot;: {
      &quot;@/*&quot;: [&quot;./src/*&quot;]
    }
  },
  &quot;include&quot;: [
    &quot;e2e/**/*.ts&quot;,
    &quot;playwright.config.ts&quot;,
    &quot;src/**/*.ts&quot;,
    &quot;src/**/*.tsx&quot;,
    &quot;vite.config.ts&quot;
  ],
  &quot;exclude&quot;: [&quot;dist&quot;, &quot;node_modules&quot;]
}
">
<input type="hidden" name="project[files][vite.config.ts]" value="import { defineConfig } from &#39;vite&#39;
import react from &#39;@vitejs/plugin-react&#39;
import { tanstackStart } from &#39;@tanstack/react-start/plugin/vite&#39;
import viteTsConfigPaths from &#39;vite-tsconfig-paths&#39;

export default defineConfig({
  plugins: [
    viteTsConfigPaths({
      projects: [`./tsconfig.json`],
    }),
    tanstackStart({
      srcDirectory: `src`,
      start: { entry: `./start.tsx` },
    }),
    react(),
  ],
})
">
<input type="hidden" name="project[files][e2e/ssr-db.spec.ts]" value="import { expect, test } from &#39;@playwright/test&#39;

test(`TanStack Start hydrates, reconciles, and incrementally applies DB rows`, async ({
  page,
  request,
}) =&gt; {
  const response = await request.get(`/ssr-db`)
  expect(response.ok()).toBe(true)

  const html = await response.text()
  expect(html).toContain(`Pay invoices`)
  expect(html).not.toContain(`Pay invoices (reconciled from sync)`)
  expect(html).toContain(`Review pull requests`)
  expect(html).toContain(`ssr`)
  expect(html).not.toContain(`Streamed from collection chunk`)

  const browserErrors: Array&lt;string&gt; = []
  page.on(`console`, (message) =&gt; {
    if (message.type() === `error`) {
      browserErrors.push(message.text())
    }
  })
  page.on(`pageerror`, (error) =&gt; {
    browserErrors.push(error.message)
  })

  await page.goto(`/ssr-db`)

  await expect(page.getByTestId(`hydration-state`)).toHaveText(`hydrated`)
  await expect(page.getByTestId(`ready-state`)).toHaveText(`ready`)
  await expect(page.getByTestId(`streamed-status`)).toHaveText(`waiting`)
  await expect(page.getByTestId(`ssr-row-count`)).toHaveText(`2`)
  await expect(page.getByTestId(`ssr-todo-list`)).toContainText(
    `Pay invoices (reconciled from sync)`,
  )
  await expect(page.getByTestId(`ssr-todo-server-1`)).toContainText(`(sync)`)
  await expect(page.getByTestId(`ssr-todo-list`)).toContainText(
    `Review pull requests`,
  )
  await expect(page.getByTestId(`ssr-todo-list`)).not.toContainText(
    `Archived roadmap`,
  )

  await page.getByTestId(`apply-stream-chunk`).click()

  await expect(page.getByTestId(`streamed-status`)).toHaveText(`streamed`)
  await expect(page.getByTestId(`ssr-row-count`)).toHaveText(`3`)
  await expect(page.getByTestId(`ssr-todo-streamed-1`)).toBeVisible()
  await expect(page.getByTestId(`ssr-todo-streamed-1`)).toContainText(
    `Streamed from collection chunk`,
  )
  expect(browserErrors).toEqual([])
})

test(`TanStack Start streams a DB result snapshot and hands off to browser sync`, async ({
  page,
  request,
}) =&gt; {
  const response = await request.get(`/ssr-db-stream`)
  expect(response.ok()).toBe(true)
  const html = await response.text()
  expect(html).toContain(`Streamed while rendering`)
  expect(html).not.toContain(`SOURCE_ONLY_DO_NOT_TRANSPORT`)

  const browserErrors: Array&lt;string&gt; = []
  page.on(`console`, (message) =&gt; {
    if (message.type() === `error`) {
      browserErrors.push(message.text())
    }
  })
  page.on(`pageerror`, (error) =&gt; {
    browserErrors.push(error.message)
  })

  await page.goto(`/ssr-db-stream`, { waitUntil: `commit` })

  await expect(page.getByTestId(`critical-todo-server-1`)).toContainText(
    `Pay invoices`,
  )
  await expect(page.getByTestId(`stream-fallback`)).toBeVisible()
  await expect(page.getByTestId(`streamed-todo-list`)).not.toBeVisible()
  await expect(page.getByTestId(`streamed-todo-streamed-server-1`)).toHaveText(
    `Streamed while rendering`,
  )
  await expect(page.getByTestId(`stream-fallback`)).not.toBeVisible()
  await expect(
    page.getByTestId(`streamed-todo-streamed-server-1`),
  ).not.toBeVisible()
  await expect(page.getByTestId(`streamed-todo-streamed-browser-1`)).toHaveText(
    `Reconciled from browser sync`,
  )
  expect(browserErrors).toEqual([])
})
">
<input type="hidden" name="project[files][src/main.tsx]" value="import { StrictMode } from &#39;react&#39;
import { createRoot } from &#39;react-dom/client&#39;
import { RouterProvider } from &#39;@tanstack/react-router&#39;
import { getRouter } from &#39;./router&#39;

const router = getRouter()

createRoot(document.getElementById(`root`)!).render(
  &lt;StrictMode&gt;
    &lt;RouterProvider router={router} /&gt;
  &lt;/StrictMode&gt;,
)
">
<input type="hidden" name="project[files][src/routeTree.gen.ts]" value="/* eslint-disable */

// @ts-nocheck

// noinspection JSUnusedGlobalSymbols

// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.

import { Route as rootRouteImport } from &#39;./routes/__root&#39;
import { Route as SsrDbStreamRouteImport } from &#39;./routes/ssr-db-stream&#39;
import { Route as SsrDbRouteImport } from &#39;./routes/ssr-db&#39;
import { Route as IndexRouteImport } from &#39;./routes/index&#39;

const SsrDbStreamRoute = SsrDbStreamRouteImport.update({
  id: &#39;/ssr-db-stream&#39;,
  path: &#39;/ssr-db-stream&#39;,
  getParentRoute: () =&gt; rootRouteImport,
} as any)
const SsrDbRoute = SsrDbRouteImport.update({
  id: &#39;/ssr-db&#39;,
  path: &#39;/ssr-db&#39;,
  getParentRoute: () =&gt; rootRouteImport,
} as any)
const IndexRoute = IndexRouteImport.update({
  id: &#39;/&#39;,
  path: &#39;/&#39;,
  getParentRoute: () =&gt; rootRouteImport,
} as any)

export interface FileRoutesByFullPath {
  &#39;/&#39;: typeof IndexRoute
  &#39;/ssr-db&#39;: typeof SsrDbRoute
  &#39;/ssr-db-stream&#39;: typeof SsrDbStreamRoute
}
export interface FileRoutesByTo {
  &#39;/&#39;: typeof IndexRoute
  &#39;/ssr-db&#39;: typeof SsrDbRoute
  &#39;/ssr-db-stream&#39;: typeof SsrDbStreamRoute
}
export interface FileRoutesById {
  __root__: typeof rootRouteImport
  &#39;/&#39;: typeof IndexRoute
  &#39;/ssr-db&#39;: typeof SsrDbRoute
  &#39;/ssr-db-stream&#39;: typeof SsrDbStreamRoute
}
export interface FileRouteTypes {
  fileRoutesByFullPath: FileRoutesByFullPath
  fullPaths: &#39;/&#39; | &#39;/ssr-db&#39; | &#39;/ssr-db-stream&#39;
  fileRoutesByTo: FileRoutesByTo
  to: &#39;/&#39; | &#39;/ssr-db&#39; | &#39;/ssr-db-stream&#39;
  id: &#39;__root__&#39; | &#39;/&#39; | &#39;/ssr-db&#39; | &#39;/ssr-db-stream&#39;
  fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
  IndexRoute: typeof IndexRoute
  SsrDbRoute: typeof SsrDbRoute
  SsrDbStreamRoute: typeof SsrDbStreamRoute
}

declare module &#39;@tanstack/react-router&#39; {
  interface FileRoutesByPath {
    &#39;/ssr-db-stream&#39;: {
      id: &#39;/ssr-db-stream&#39;
      path: &#39;/ssr-db-stream&#39;
      fullPath: &#39;/ssr-db-stream&#39;
      preLoaderRoute: typeof SsrDbStreamRouteImport
      parentRoute: typeof rootRouteImport
    }
    &#39;/ssr-db&#39;: {
      id: &#39;/ssr-db&#39;
      path: &#39;/ssr-db&#39;
      fullPath: &#39;/ssr-db&#39;
      preLoaderRoute: typeof SsrDbRouteImport
      parentRoute: typeof rootRouteImport
    }
    &#39;/&#39;: {
      id: &#39;/&#39;
      path: &#39;/&#39;
      fullPath: &#39;/&#39;
      preLoaderRoute: typeof IndexRouteImport
      parentRoute: typeof rootRouteImport
    }
  }
}

const rootRouteChildren: RootRouteChildren = {
  IndexRoute: IndexRoute,
  SsrDbRoute: SsrDbRoute,
  SsrDbStreamRoute: SsrDbStreamRoute,
}
export const routeTree = rootRouteImport
  ._addFileChildren(rootRouteChildren)
  ._addFileTypes&lt;FileRouteTypes&gt;()

import type { getRouter } from &#39;./router.tsx&#39;
import type { startInstance } from &#39;./start.tsx&#39;
declare module &#39;@tanstack/react-start&#39; {
  interface Register {
    ssr: true
    router: Awaited&lt;ReturnType&lt;typeof getRouter&gt;&gt;
    config: Awaited&lt;ReturnType&lt;typeof startInstance.getOptions&gt;&gt;
  }
}
">
<input type="hidden" name="project[files][src/router.tsx]" value="import { createRouter as createTanstackRouter } from &#39;@tanstack/react-router&#39;
import { createIsomorphicFn } from &#39;@tanstack/react-start&#39;
import { DbClient } from &#39;@tanstack/react-db&#39;
import { routerWithDbClient } from &#39;@tanstack/react-router-with-db&#39;
import { routeTree } from &#39;./routeTree.gen&#39;
import &#39;./styles.css&#39;

export type RouterContext = {
  dbClient: DbClient
}

const getRuntime = createIsomorphicFn()
  .server(() =&gt; `server` as const)
  .client(() =&gt; `browser` as const)

export function getRouter() {
  const dbClient = new DbClient({
    runtime: getRuntime(),
  })
  const router = createTanstackRouter({
    routeTree,
    context: { dbClient },
    scrollRestoration: true,
  })

  return routerWithDbClient(router, dbClient)
}
">
<input type="hidden" name="project[files][src/start.tsx]" value="import { createStart } from &#39;@tanstack/react-start&#39;

export const startInstance = createStart(() =&gt; {
  return {
    defaultSsr: true,
  }
})
">
<input type="hidden" name="project[files][src/styles.css]" value="body {
  margin: 0;
  font-family:
    Inter,
    ui-sans-serif,
    system-ui,
    -apple-system,
    BlinkMacSystemFont,
    &#39;Segoe UI&#39;,
    sans-serif;
}

button {
  font: inherit;
}
">
<input type="hidden" name="project[files][netlify/functions/server.mjs]" value="import server from &#39;../../dist/server/server.js&#39;

export const config = {
  path: &#39;/*&#39;,
  preferStatic: true,
}

export default function handler(request) {
  return server.fetch(request)
}
">
<input type="hidden" name="project[files][src/routes/__root.tsx]" value="import * as React from &#39;react&#39;
import {
  HeadContent,
  Outlet,
  Scripts,
  createRootRouteWithContext,
} from &#39;@tanstack/react-router&#39;
import appCss from &#39;../styles.css?url&#39;
import type { RouterContext } from &#39;../router&#39;

export const Route = createRootRouteWithContext&lt;RouterContext&gt;()({
  head: () =&gt; ({
    meta: [
      {
        charSet: `utf-8`,
      },
      {
        name: `viewport`,
        content: `width=device-width, initial-scale=1`,
      },
      {
        title: `TanStack DB Start SSR E2E`,
      },
    ],
    links: [
      {
        rel: `stylesheet`,
        href: appCss,
      },
    ],
  }),
  shellComponent: RootDocument,
  component: () =&gt; &lt;Outlet /&gt;,
})

function RootDocument({ children }: { children: React.ReactNode }) {
  return (
    &lt;html lang=&quot;en&quot;&gt;
      &lt;head&gt;
        &lt;HeadContent /&gt;
      &lt;/head&gt;
      &lt;body&gt;
        {children}
        &lt;Scripts /&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  )
}
">
<input type="hidden" name="project[files][src/routes/index.tsx]" value="import { Link, createFileRoute } from &#39;@tanstack/react-router&#39;

export const Route = createFileRoute(`/`)({
  component: HomePage,
})

function HomePage() {
  return (
    &lt;main style={{ padding: 32 }}&gt;
      &lt;h1&gt;TanStack DB Start SSR E2E&lt;/h1&gt;
      &lt;Link to=&quot;/ssr-db&quot;&gt;Open SSR DB route&lt;/Link&gt;
    &lt;/main&gt;
  )
}
">
<input type="hidden" name="project[files][src/routes/ssr-db-stream.tsx]" value="import * as React from &#39;react&#39;
import { createFileRoute } from &#39;@tanstack/react-router&#39;
import {
  collectionOptions,
  eq,
  useLiveQuery,
  useLiveSuspenseQuery,
} from &#39;@tanstack/react-db&#39;
import { preloadSsrTodos, ssrTodoCollection } from &#39;../lib/ssr-fixture&#39;

type StreamedTodo = {
  id: string
  text: string
  status: `open` | `done`
  sourcePayload: string
}

const serverTodo: StreamedTodo = {
  id: `streamed-server-1`,
  text: `Streamed while rendering`,
  status: `open`,
  sourcePayload: `SOURCE_ONLY_DO_NOT_TRANSPORT`,
}

const browserTodo: StreamedTodo = {
  id: `streamed-browser-1`,
  text: `Reconciled from browser sync`,
  status: `open`,
  sourcePayload: `BROWSER_SOURCE_ONLY_DO_NOT_TRANSPORT`,
}

const streamedTodoCollection = collectionOptions(
  `ssr-suspense-stream-todos`,
  (client) =&gt; {
    const runtime = client.requireDependency&lt;`server` | `browser`&gt;(`runtime`)

    return {
      id: `ssr-suspense-stream-todos`,
      getKey: (todo: StreamedTodo) =&gt; todo.id,
      syncMode: `on-demand` as const,
      sync: {
        sync: ({ begin, write, commit, markReady }) =&gt; {
          markReady()

          return {
            loadSubset: () =&gt; {
              return new Promise&lt;void&gt;((resolve) =&gt; {
                setTimeout(
                  () =&gt; {
                    begin({ immediate: true })
                    write({
                      type: `insert`,
                      value: runtime === `server` ? serverTodo : browserTodo,
                    })
                    commit()
                    resolve()
                  },
                  runtime === `server` ? 1000 : 1500,
                )
              })
            },
          }
        },
      },
    }
  },
)

export const Route = createFileRoute(`/ssr-db-stream`)({
  loader: async ({ context }) =&gt; {
    await preloadSsrTodos(context.dbClient)
  },
  component: SsrDbStreamRoute,
})

function SsrDbStreamRoute() {
  return (
    &lt;main data-testid=&quot;ssr-db-stream-page&quot;&gt;
      &lt;h1&gt;TanStack DB Suspense Streaming&lt;/h1&gt;
      &lt;CriticalTodoList /&gt;
      &lt;React.Suspense
        fallback={&lt;p data-testid=&quot;stream-fallback&quot;&gt;Loading todos&lt;/p&gt;}
      &gt;
        &lt;StreamedTodoList /&gt;
      &lt;/React.Suspense&gt;
    &lt;/main&gt;
  )
}

function CriticalTodoList() {
  const { data: todos } = useLiveQuery({
    query: (q) =&gt;
      q
        .from({ todo: ssrTodoCollection })
        .where(({ todo }) =&gt; eq(todo.status, `open`)),
  })

  return (
    &lt;ul data-testid=&quot;critical-todo-list&quot;&gt;
      {todos.map((todo) =&gt; (
        &lt;li data-testid={`critical-todo-${todo.id}`} key={todo.id}&gt;
          {todo.text}
        &lt;/li&gt;
      ))}
    &lt;/ul&gt;
  )
}

function StreamedTodoList() {
  const { data: todos } = useLiveSuspenseQuery({
    query: (q) =&gt;
      q
        .from({ todo: streamedTodoCollection })
        .where(({ todo }) =&gt; eq(todo.status, `open`))
        .select(({ todo }) =&gt; ({
          id: todo.id,
          text: todo.text,
          status: todo.status,
        })),
  })

  return (
    &lt;ul data-testid=&quot;streamed-todo-list&quot;&gt;
      {todos.map((todo) =&gt; (
        &lt;li data-testid={`streamed-todo-${todo.id}`} key={todo.id}&gt;
          {todo.text}
        &lt;/li&gt;
      ))}
    &lt;/ul&gt;
  )
}
">
<input type="hidden" name="project[files][src/routes/ssr-db.tsx]" value="import * as React from &#39;react&#39;
import { createFileRoute } from &#39;@tanstack/react-router&#39;
import { eq, useLiveQuery } from &#39;@tanstack/react-db&#39;
import {
  applyStreamedTodo,
  createDehydratedSsrTodoState,
  ssrTodoCollection,
} from &#39;../lib/ssr-fixture&#39;
import type { DbClient } from &#39;@tanstack/react-db&#39;

export const Route = createFileRoute(`/ssr-db`)({
  loader: async () =&gt; {
    return {
      dbState: await createDehydratedSsrTodoState(),
    }
  },
  component: SsrDbRoute,
})

function SsrDbRoute() {
  const { dbState } = Route.useLoaderData()
  const { dbClient } = Route.useRouteContext()
  const [hydratedDbClient] = React.useState(() =&gt; {
    dbClient.hydrate(dbState)
    return dbClient
  })

  return &lt;SsrDbTodos dbClient={hydratedDbClient} /&gt;
}

function SsrDbTodos({ dbClient }: { dbClient: DbClient }) {
  const [hydrated, setHydrated] = React.useState(false)
  const [streamed, setStreamed] = React.useState(false)
  const { data: todos, isReady } = useLiveQuery({
    query: (q) =&gt;
      q
        .from({ todo: ssrTodoCollection })
        .where(({ todo }) =&gt; eq(todo.status, `open`))
        .orderBy(({ todo }) =&gt; todo.id, `asc`),
  })

  React.useEffect(() =&gt; {
    setHydrated(true)
  }, [])

  return (
    &lt;main
      data-testid=&quot;ssr-db-page&quot;
      style={{
        background: `#f8fafc`,
        minHeight: `100vh`,
        padding: 32,
      }}
    &gt;
      &lt;section
        style={{
          background: `white`,
          border: `1px solid #e5e7eb`,
          borderRadius: 8,
          margin: `0 auto`,
          maxWidth: 720,
          padding: 24,
        }}
      &gt;
        &lt;h1&gt;TanStack DB SSR&lt;/h1&gt;

        &lt;div style={{ display: `flex`, gap: 16, marginBottom: 16 }}&gt;
          &lt;span data-testid=&quot;hydration-state&quot;&gt;
            {hydrated ? `hydrated` : `ssr`}
          &lt;/span&gt;
          &lt;span data-testid=&quot;ready-state&quot;&gt;{isReady ? `ready` : `loading`}&lt;/span&gt;
          &lt;span data-testid=&quot;streamed-status&quot;&gt;
            {streamed ? `streamed` : `waiting`}
          &lt;/span&gt;
          &lt;span&gt;
            rows: &lt;strong data-testid=&quot;ssr-row-count&quot;&gt;{todos.length}&lt;/strong&gt;
          &lt;/span&gt;
        &lt;/div&gt;

        &lt;ul data-testid=&quot;ssr-todo-list&quot;&gt;
          {todos.map((todo) =&gt; (
            &lt;li data-testid={`ssr-todo-${todo.id}`} key={todo.id}&gt;
              {todo.text} &lt;small&gt;({todo.source})&lt;/small&gt;
            &lt;/li&gt;
          ))}
        &lt;/ul&gt;

        &lt;button
          data-testid=&quot;apply-stream-chunk&quot;
          onClick={() =&gt; {
            applyStreamedTodo(dbClient)
            setStreamed(true)
          }}
          style={{
            background: `#15803d`,
            border: 0,
            borderRadius: 6,
            color: `white`,
            cursor: `pointer`,
            marginTop: 16,
            padding: `10px 14px`,
          }}
          type=&quot;button&quot;
        &gt;
          Apply streamed chunk
        &lt;/button&gt;
      &lt;/section&gt;
    &lt;/main&gt;
  )
}
">
<input type="hidden" name="project[files][src/lib/ssr-fixture.ts]" value="import { DbClient, collectionOptions, eq } from &#39;@tanstack/react-db&#39;
import type { DehydratedDbState } from &#39;@tanstack/react-db&#39;

export type SsrTodo = {
  id: string
  text: string
  status: `open` | `done`
  source: `server` | `sync` | `stream`
}

export const ssrTodoCollectionId = `ssr-e2e-todos`

const serverTodos: Array&lt;SsrTodo&gt; = [
  {
    id: `server-1`,
    text: `Pay invoices`,
    status: `open`,
    source: `server`,
  },
  {
    id: `server-2`,
    text: `Review pull requests`,
    status: `open`,
    source: `server`,
  },
  {
    id: `server-3`,
    text: `Archived roadmap`,
    status: `done`,
    source: `server`,
  },
]

const browserTodos: Array&lt;SsrTodo&gt; = serverTodos.map((todo) =&gt;
  todo.id === `server-1`
    ? {
        ...todo,
        text: `Pay invoices (reconciled from sync)`,
        source: `sync`,
      }
    : { ...todo, source: `sync` },
)

export const streamedTodo: SsrTodo = {
  id: `streamed-1`,
  text: `Streamed from collection chunk`,
  status: `open`,
  source: `stream`,
}

export const ssrTodoCollection = collectionOptions(ssrTodoCollectionId, () =&gt; ({
  id: ssrTodoCollectionId,
  getKey: (todo: SsrTodo) =&gt; todo.id,
  syncMode: `on-demand`,
  sync: {
    sync: ({ begin, write, commit, markReady }) =&gt; {
      markReady()

      return {
        loadSubset: () =&gt; {
          const todos =
            typeof window === `undefined` ? serverTodos : browserTodos

          begin({ immediate: true })
          for (const todo of todos) {
            write({
              type: `insert`,
              value: todo,
            })
          }
          commit()
          return true
        },
      }
    },
  },
}))

export async function preloadSsrTodos(dbClient: DbClient): Promise&lt;void&gt; {
  await dbClient.preloadLiveQuery({
    query: (q) =&gt;
      q
        .from({ todo: ssrTodoCollection })
        .where(({ todo }) =&gt; eq(todo.status, `open`)),
  })
}

export async function createDehydratedSsrTodoState(): Promise&lt;DehydratedDbState&gt; {
  const dbClient = new DbClient()
  try {
    await preloadSsrTodos(dbClient)
    return dbClient.dehydrate()
  } finally {
    await dbClient.cleanup()
  }
}

export function applyStreamedTodo(dbClient: DbClient): void {
  dbClient.applyCollectionChunk({
    collectionId: ssrTodoCollectionId,
    rows: [
      {
        key: streamedTodo.id,
        value: streamedTodo,
      },
    ],
  })
}
">
<input type="hidden" name="project[description]" value="generated by https://pkg.pr.new">
<input type="hidden" name="project[template]" value="node">
<input type="hidden" name="project[title]" value="@tanstack/db-example-react-start-ssr-e2e">
</form>
<script>document.getElementById("mainForm").submit();</script>

</body></html>