Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

ssr.md

1,009 lines32.8 KB

1---
2title: SSR and Hydration
3id: ssr
4---
5​
6TanStack DB SSR transports the smallest useful snapshot for the work the server
7performed:
8​
9- Explicitly preloaded collections dehydrate as normalized collection rows.
10- Preloaded or render-discovered live queries dehydrate as ordered query-result
11 snapshots, without serializing all of their source collections.
12​
13The browser renders either snapshot immediately, starts its normal collection
14sync and live-query pipeline, then atomically replaces a live-query snapshot
15when the browser result becomes authoritative.
16​
17## High-level Summary
18​
19The SSR-friendly API adds six concepts:
20​
21- `DbClient` owns materialized collection instances for one request, browser app,
22 test, or script.
23- `collectionOptions(...)` creates a stable collection descriptor. Reusable
24 descriptors create fresh adapter config for each `DbClient`.
25- `dbClient.dehydrate()`, `dbClient.hydrate(state)`, and
26 `dbClient.applyCollectionChunk(chunk)` move explicit collection state across
27 the server/client boundary.
28- `dbClient.preloadLiveQuery(options)` captures only the ordered result of a
29 live query for hydration or streaming.
30- React and Svelte apps use `DbProvider` so hooks can resolve collection
31 descriptors against the current client.
32- `@tanstack/react-router-with-db` streams live queries discovered by Suspense
33 during a TanStack Start server render.
34​
35`createCollection(...)` and direct collection instances remain supported.
36Adopt descriptors and a `DbClient` when you want SSR-safe request isolation,
37hydration, incremental chunks, or Suspense streaming. These APIs were already
38available in 0.9.2; adopting SSR is optional when upgrading to the RC. For the
39breaking changes from 0.9.2, see
40[Migrating to the 1.0 RC](./migrate-to-1-0-rc.md).
41​
42The dependency-array form was removed in the first 1.0 RC:
43​
44```tsx
45useLiveQuery((q) => q.from({ todos }).where(...), [status])
46```
47​
48Use the query config form instead:
49​
50```tsx
51useLiveQuery({
52 query: (q) => q.from({ todos: todoCollection }).where(...),
53})
54```
55​
56React derives live query identity from structured query IR by default. Add
57`queryKey` only for opaque functional query logic or for a hot render path where
58you want to skip derived identity work.
59​
60If the old dependency array tracked a Collection object that you replace while
61the hook stays mounted, give the replacement a distinct ID. A different source
62object with the same ID now throws in the derived-identity form. To reuse the
63ID, unmount the old hook, clean up its source and client scope, then mount the
64replacement.
65​
66## Cheat Sheet
67​
68| Task | Before | SSR-friendly |
69| --- | --- | --- |
70| Define a collection | `createCollection(options)` | `collectionOptions(id, factory)` |
71| Materialize a collection | module-level singleton | `dbClient.collection(todoCollection)` |
72| Scope collection state | module lifetime | `new DbClient()` per request/browser/test |
73| Provide React context | none | `<DbProvider client={dbClient}>` |
74| Query from React | direct collection instance | descriptor in `from`, resolved by `DbProvider` |
75| Mutate from React | import singleton collection | `useDbClient().collection(todoCollection)` |
76| Server preload | ad hoc collection preload | `collection.preload()` or `dbClient.preloadLiveQuery(...)` |
77| Serialize SSR state | none | `const state = dbClient.dehydrate()` |
78| Hydrate in browser | none | `dbClient.hydrate(state)` before hooks read it |
79| Apply rows incrementally | custom app state | `dbClient.applyCollectionChunk(chunk)` |
80| Stream render-time results | none | `routerWithDbClient(router, dbClient)` |
81| React query identity | dependency array | derived IR, or `queryKey` when needed |
82​
83Building or extending a Query keeps descriptors in its plan without starting
84their source Collections. The client-aware hook or `dbClient.preloadLiveQuery()`
85binds the finished plan when it consumes it. Reuse the original unbound Query
86across clients; a prepared Query contains Collections from the client that
87prepared it.
88​
89### Minimal React Pattern
90​
91```tsx
92import {
93 DbClient,
94 DbProvider,
95 Query,
96 collectionOptions,
97 eq,
98 useDbClient,
99 useLiveQuery,
100} from '@tanstack/react-db'
101​
102const todoCollection = collectionOptions('todos', () => ({
103 id: 'todos',
104 getKey: (todo: Todo) => todo.id,
105 sync: {
106 sync: ({ markReady }) => {
107 markReady()
108 },
109 },
110}))
111​
112function useTodoCollection() {
113 return useDbClient().collection(todoCollection)
115​
116function Todos({ status }: { status: string }) {
117 const todos = useTodoCollection()
118​
119 const { data } = useLiveQuery({
120 query: (q) =>
121 q
122 .from({ todo: todoCollection })
123 .where(({ todo }) => eq(todo.status, status)),
124 })
125​
126 return (
127 <ul>
128 {data.map((todo) => (
129 <li
130 key={todo.id}
131 onClick={() => todos.update(todo.id, (draft) => {
132 draft.done = true
133 })}
134 >
135 {todo.title}
136 </li>
137 ))}
138 </ul>
139 )
141​
142const dbClient = new DbClient()
143​
144root.render(
145 <DbProvider client={dbClient}>
146 <Todos status="open" />
147 </DbProvider>
149```
150​
151A descriptor query can also be defined outside React, without a `DbClient` at
152definition time:
153​
154```tsx
155const openTodosQuery = new Query()
156 .from({ todo: todoCollection })
157 .where(({ todo }) => eq(todo.status, 'open'))
158​
159function OpenTodos() {
160 const { data } = useLiveQuery({ query: openTodosQuery })
161 return <span>{data.length} open todos</span>
163```
164​
165The consuming hook binds this query to its `DbProvider` client. The same query
166can be used with `dbClient.preloadLiveQuery({ query: openTodosQuery })` on the
167server, or under another provider with a different client. For that reuse, the
168descriptor must have a reusable factory. Executing a descriptor query without
169a client throws when the source Collection is needed.
170​
171The factory matters when config contains mutable adapter state or closures.
172Every `DbClient` gets a fresh config and collection instance. First-party
173adapter option creators already attach an equivalent factory, so this is also
174safe:
175​
176```tsx
177const todoCollection = collectionOptions(
178 localOnlyCollectionOptions<Todo>({
179 id: 'todos',
180 getKey: (todo) => todo.id,
181 })
183```
184​
185Within one `DbClient`, descriptors with the same `id` resolve to the same
186collection. Only the first descriptor is materialized. Include every dynamic
187parameter that changes the collection in its `id`.
188​
189A descriptor created from an arbitrary concrete config can be materialized by
190one `DbClient` only. Use the explicit factory form for custom adapters and
191request-scoped dependencies.
192​
193## SSR Flow
194​
195The server and browser use the same descriptors, but different `DbClient`
196instances.
197​
198```txt
199server request
200 -> new DbClient()
201 -> preload an explicit collection or live-query result
202 -> dbClient.dehydrate()
203 -> send state through framework loader
204​
205browser
206 -> new DbClient()
207 -> dbClient.hydrate(loaderState)
208 -> <DbProvider client={dbClient}>
209 -> useLiveQuery({ query })
210 -> start source sync
211 -> atomically replace any query snapshot with the live result
212```
213​
214During React hydration, descriptor-backed queries read either hydrated
215collection rows or their matching query-result snapshot for the first browser
216render. Adapter sync and queued on-demand loads start when React commits the
217external-store subscription, so the initial markup still matches the server.
218The snapshot remains visible while the source is loading. Once the browser live
219query is ready, DB publishes one handoff from the snapshot to the live result.
220​
221A hydrated query hash identifies a portable result, but the payload does not
222contain the server's Collection objects. The first browser hook that commits a
223subscription, or the first browser `preloadLiveQuery()` call, claims the local
224source Collections for that reusable result. While the result is pending or
225successful, later local consumers with the same hash must use those Collection
226objects in the same query positions. A different source object with the same ID
227is rejected; give a genuinely different query a distinct `queryKey`. A newer
228hydration chunk updates the result without changing its established claim.
229`useLiveSuspenseQuery` can preload during render, claiming a source even if
230React never commits that render. A failed stream releases its claim, so a newer
231hydrated result can accept the first healthy local source. Once a subscribed
232live result becomes authoritative, the client consumes the stream;
233a later observer uses its own source Collection, even under the same hash.
234​
235### Server
236​
237Create a fresh `DbClient` for each request. Materialize descriptors through that
238client, preload the data needed for the route, and dehydrate the client.
239​
240```tsx
241import { DbClient, collectionOptions, eq } from '@tanstack/db'
242​
243export const todoCollection = collectionOptions('todos', () => ({
244 id: 'todos',
245 getKey: (todo: Todo) => todo.id,
246 syncMode: 'on-demand',
247 sync: {
248 sync: ({ markReady, begin, write, commit }) => {
249 markReady()
250​
251 return {
252 loadSubset: async () => {
253 const todos = await api.todos.list()
254 begin()
255 for (const todo of todos) {
256 write({ type: 'insert', value: todo })
257 }
258 commit()
259 return true
260 },
261 }
262 },
263 },
264}))
265​
266export async function loadTodosForSsr() {
267 const dbClient = new DbClient()
268 const todos = dbClient.collection(todoCollection)
269 await todos.preload()
270​
271 return dbClient.dehydrate()
273```
274​
275This explicit collection preload dehydrates normalized source rows. Use it when
276multiple browser queries need the same source data.
277​
278If the source is much larger than the rendered result, preload the query instead:
279​
280```tsx
281const dbClient = new DbClient()
282​
283await dbClient.preloadLiveQuery({
284 query: (q) =>
285 q
286 .from({ todo: todoCollection })
287 .where(({ todo }) => eq(todo.status, 'open'))
288 .select(({ todo }) => ({ id: todo.id, title: todo.title })),
289})
290​
291const state = dbClient.dehydrate()
292```
293​
294This payload contains the projected query result and no source collection rows
295unless that collection was also materialized explicitly.
296​
297Use the config object form in both the loader and the hook when they share a
298preloaded result:
299​
300```tsx
301const openTodos = {
302 query: (q: InitialQueryBuilder) =>
303 q.from({ todo: todoCollection }).where(({ todo }) => eq(todo.status, 'open')),
305​
306await dbClient.preloadLiveQuery(openTodos)
307// In the component:
308const { data } = useLiveQuery(openTodos)
309```
310​
311The function form `useLiveQuery(openTodos.query)` currently derives a different
312identity from `useLiveQuery(openTodos)`. It will not reuse the loader's result.
313Sharing the query callback alone is insufficient. To use an explicit `queryKey`,
314pass config objects with the same `queryKey` to both `preloadLiveQuery` and
315`useLiveQuery`. Their sources and result configuration must still describe the
316same query.
317​
318### Prepare every server snapshot
319​
320An ordinary server hook can render empty/loading state without a preload. To
321render data, await a matching `preloadLiveQuery()` or explicitly preload the
322source Collections. A different query warming the same source does not prepare
323this query's result for transport. Reading those incidental rows or their
324readiness during SSR throws an error with the required preparation steps.
325Normal browser reads and runtime query errors keep their usual behavior.
326​
327Normalized source transport carries rows without query readiness. When a server
328hook reads explicitly prepared sources, it captures the query's render-time
329rows and status as a query result. Ready prepared queries can therefore finish
330non-streaming Suspense; loading queries remain loading. Later server writes and
331browser writes before hydration do not change that initial view. Browser commit
332starts acquisition and publishes the live status normally. A loading capture
333does not complete an explicit data preload.
334​
335An ordinary hook can render loading before a Suspense sibling completes the
336same query. Each hook retains its own server-rendered view during hydration.
337The Router stream forwards a newer result for that query without replacing the
338ordinary hook's earlier view. A later boundary waits for its missing streamed
339result instead of substituting browser rows. DbClient retains transported server
340snapshots until cleanup, so one reader's commit cannot consume another
341boundary's initial view. New ordinary browser reads still use live results.
342​
343Streaming `useLiveSuspenseQuery` discovers and prepares its result during render,
344including when another query already warmed the source. Ordinary hooks require
345explicit preparation to render that data. Opaque SSR queries require a serializable
346`queryKey`, including when the source is already warm.
347​
348For `useLiveInfiniteQuery`, preload the initial window plus its one-row peek:
349​
350```tsx
351const orderedTodos = new Query()
352 .from({ todo: todoCollection })
353 .orderBy(({ todo }) => todo.id)
354const pageSize = 20
355​
356await dbClient.preloadLiveQuery({
357 query: orderedTodos.limit(pageSize + 1).offset(0),
358})
359// In the component:
360const result = useLiveInfiniteQuery(() => orderedTodos, { pageSize })
361```
362​
363With an explicit `queryKey`, the DbClient query hash also includes limit and
364offset. Use the same initial window in the preload and the infinite hook.
365​
366Custom dehydration filters must retain the query result that the markup requires.
367​
368### Indexes before query compilation
369​
370Create manual indexes when initializing each request or browser client, before
371preloading or rendering queries that use them:
372​
373```tsx
374import { BasicIndex, DbClient, type CollectionOptions } from '@tanstack/db'
375​
376function createDbClient(todoCollection: CollectionOptions<{ id: string }>) {
377 const client = new DbClient()
378 client.collection(todoCollection).createIndex((todo) => todo.id, {
379 indexType: BasicIndex,
380 })
381 return client
383```
384​
385Collection materialization does not start sync unless its config requests it.
386An index installed inside the sync callback can arrive after the ordered query
387has compiled. `autoIndex: 'eager'` with `defaultIndexType: BasicIndex` is an
388alternative when indexes should be created as queries compile. Descriptors
389currently have no `indexes` or `onCreate` option.
390​
391### Preload lifetime
392​
393`preloadLiveQuery()` has no built-in deadline or `AbortSignal` option. A source
394that keeps retrying without becoming ready can keep its preload pending. Apply
395an application deadline to request work and clean up its request-scoped client
396when abandoning it; a timer race alone does not stop the underlying sync.
397​
398Preloaded results belong to the client. There is no public method to release
399one preloaded query. `cleanup()` releases the entire client and its Collections.
400Avoid accumulating route-specific preloads in a browser client without an
401application lifetime policy. A separately owned `createLiveQueryCollection()`
402can be preloaded and cleaned up explicitly when per-query ownership is needed.
403​
404### Browser
405​
406Hydrate the browser client before rendering components that read from DB.
407​
408```tsx
409import {
410 DbClient,
411 DbProvider,
412 HydrationBoundary,
413} from '@tanstack/react-db'
414​
415function App({ dehydratedDbState }: { dehydratedDbState: DehydratedDbState }) {
416 const [dbClient] = React.useState(() => new DbClient())
417​
418 return (
419 <DbProvider client={dbClient}>
420 <HydrationBoundary state={dehydratedDbState}>
421 <Routes />
422 </HydrationBoundary>
423 </DbProvider>
424 )
426```
427​
428Frameworks differ in how loader data reaches the client, but the DB handoff is
429the same: `DbClient` on the server, `dehydrate()`, then `hydrate()` into the
430browser client.
431​
432### Svelte
433​
434Svelte resolves descriptors from its own `DbProvider` and reads hydrated query
435snapshots synchronously during server rendering:
436​
437```svelte
438<script lang="ts">
439 import { DbClient, DbProvider } from '@tanstack/svelte-db'
440 import Todos from './Todos.svelte'
441​
442 const client = new DbClient()
443 client.hydrate(dehydratedDbState)
444</script>
445​
446<DbProvider {client} hydrating>
447 <Todos />
448</DbProvider>
449```
450​
451Inside `Todos.svelte`, `useLiveQuery({ query })` can use collection descriptors
452directly. The browser subscription starts source sync and performs the same
453snapshot-to-live-result handoff as React.
454​
455Set `hydrating` for each root initialized with Svelte's `hydrate()`. It preserves
456that root's server public snapshot even after another root publishes browser
457rows. Nested providers inherit it unless they specify another value. The
458provider clears it after mount, so later children read live rows. Omit it for
459ordinary `mount()` calls.
460​
461Hooks that pass `client` explicitly also need a marked provider around their
462hydrated subtree. The client alone cannot identify hydration versus a fresh mount.
463​
464Live demo: https://tanstack-db-ssr-demo.netlify.app/ssr-db
465​
466## Suspense Streaming with TanStack Start
467​
468`@tanstack/react-router-with-db` follows the same integration pattern as
469`@tanstack/react-router-with-query`:
470​
471```tsx
472import { DbClient } from '@tanstack/react-db'
473import { createRouter } from '@tanstack/react-router'
474import { routerWithDbClient } from '@tanstack/react-router-with-db'
475​
476export type RouterContext = {
477 dbClient: DbClient
479​
480export function getRouter() {
481 const dbClient = new DbClient()
482 const router = createRouter({
483 routeTree,
484 context: { dbClient },
485 })
486​
487 return routerWithDbClient(router, dbClient)
489```
490​
491The adapter adds `dbClient` to router context, wraps the app in `DbProvider`,
492dehydrates critical state, and opens a stream for query results discovered later
493during rendering.
494​
495```tsx
496function RouteComponent() {
497 return (
498 <Suspense fallback={<p>Loading todos</p>}>
499 <TodoList />
500 </Suspense>
501 )
503​
504function TodoList() {
505 const { data } = useLiveSuspenseQuery({
506 query: (q) =>
507 q
508 .from({ todo: todoCollection })
509 .where(({ todo }) => eq(todo.status, 'open')),
510 })
511​
512 return data.map((todo) => <Todo key={todo.id} todo={todo} />)
514```
515​
516When `TodoList` suspends on the server, the adapter streams the pending query
517promise. That promise resolves to the ordered live-query result snapshot inside
518the streamed `DehydratedDbState`. The source collections and D2 graph do not
519cross the wire. The browser shows the snapshot, starts the source collections
520and live query normally, then replaces the snapshot when the browser result is
521ready.
522​
523The server and browser must derive the same live-query identity. Structured
524queries do this automatically. An opaque query must provide a serializable
525`queryKey`; render-time streaming throws if it cannot derive an identity.
526​
527## Suspense Streaming with Next.js
528​
529Next.js App Router can transport the same pending query promise through React
530Server Components. Start the preload without awaiting it, dehydrate the pending
531result, and pass that state to a client hydration boundary:
532​
533```tsx
534export default function Page() {
535 const dbClient = new DbClient()
536 void dbClient.preloadLiveQuery({ query: openTodosQuery })
537​
538 const state = dbClient.dehydrate({
539 shouldDehydrateCollection: () => false,
540 shouldDehydrateLiveQuery: () => true,
541 })
542​
543 return (
544 <DbHydration state={state}>
545 <Suspense fallback={<p>Loading todos</p>}>
546 <TodoList />
547 </Suspense>
548 </DbHydration>
549 )
551```
552​
553`DbHydration` is a client component that creates one browser `DbClient`, wraps
554children in `DbProvider`, and passes `state` to `HydrationBoundary`. React streams
555the promise result into that boundary. The full working integration is in
556`examples/react/next-ssr-e2e`.
557​
558## Incremental Collection Hydration
559​
560Applications can also apply collection rows received through their own stream.
561Incremental hydration uses the same collection chunk shape as holistic
562dehydration:
563​
564```ts
565dbClient.applyCollectionChunk({
566 collectionId: 'todos',
567 rows: [
568 {
569 key: 'todo-1',
570 value: {
571 id: 'todo-1',
572 title: 'Streamed row',
573 status: 'open',
574 },
575 metadata: { source: 'stream' },
576 },
577 ],
578 syncMeta: { version: 1, cursor: 'abc' },
579})
580```
581​
582If the target collection is already materialized, the rows apply immediately and
583existing live queries react from collection state. If the collection is not
584materialized yet, the chunk is stored and applied when that `collectionId`
585materializes.
586​
587## What Gets Serialized
588​
589`dbClient.dehydrate()` can emit two independent snapshot types.
590​
591Serialized:
592​
593- explicit collection snapshots: collection id, synced row keys and values, row
594 metadata, and adapter sync metadata from `exportSyncMeta`
595- live-query snapshots: query hash and ordered result rows; completed explicit
596 preloads are included by default, while framework integrations opt pending
597 promises into streaming
598​
599Not serialized:
600​
601- mutation handlers
602- pending optimistic mutations
603- pending subscriptions
604- D2 graphs or compiled pipelines
605- transaction stacks
606- module-level runtime state
607- source collection rows for a query-result snapshot, unless that collection was
608 also explicitly materialized for dehydration
609​
610Choose the payload unit according to what the browser needs. Explicit collection
611preloading preserves normalized rows for reuse across queries. Live-query
612preloading avoids shipping a 50-100x larger source when the rendered projection
613is small. Neither mode serializes executable query state.
614​
615## Sync Metadata
616​
617Adapters can participate in resumable sync with three optional hooks:
618​
619```ts
620type SyncConfig = {
621 exportSyncMeta?: () => unknown
622 importSyncMeta?: (meta: unknown) => void
623 mergeSyncMeta?: (current: unknown, incoming: unknown) => unknown
625```
626​
627The metadata shape is adapter-owned. Version it inside the adapter payload. If an
628adapter cannot understand incoming metadata, it should ignore it and restart
629sync from a safe point.
630​
631During hydration, DB imports `syncMeta` into the materialized collection. If the
632collection already has current metadata, DB calls `mergeSyncMeta(current,
633incoming)` when provided and imports the merged result.
634​
635If an adapter does not implement sync metadata hooks, row snapshots still hydrate
636and the adapter can restart sync normally.
637​
638## Initial Data
639​
640`initialData` is a startup seed, not a sync-ready signal.
641​
642Before adapter sync starts, current `DbClient` precedence from lowest to highest
643is:
644​
6451. per-materialization `initialData`
6462. persisted rows
6473. hydrated rows
648​
649Fresh adapter sync is authoritative over all three. Hydrated and initial rows
650are provisional base state. The adapter's first insert for the same key
651replaces the provisional row and its row metadata instead of raising a
652duplicate-key error; an insert without metadata clears the seed's metadata.
653An adapter update merges over the provisional row like any update. A hydrated
654row that arrives after the adapter has written its key, or while the adapter's
655transaction for it is open, does not change what the adapter wrote: it only
656supplies a row or row metadata that the adapter has not written. Row data and
657row metadata count separately, so a later hydrated row can still supply
658metadata for a key whose row the adapter only updated. After an adapter delete
659or truncate, a later hydrated row does not bring the key back. Among hydrated
660rows for a key the adapter has not written, the latest one wins, including its
661row metadata or the lack of it.
662​
663Hydrated rows and `initialData` never mark adapter sync as ready by themselves.
664The adapter still owns readiness through its sync lifecycle.
665​
666## React Query Identity
667​
668React hooks derive live query identity from structured query IR by default:
669​
670```tsx
671function Todos({ status }: { status: string }) {
672 return useLiveQuery({
673 query: (q) =>
674 q
675 .from({ todo: todoCollection })
676 .where(({ todo }) => eq(todo.status, status)),
677 })
679```
680​
681The captured `status` value is represented in the structured IR, so no
682dependency array or `queryKey` is required.
683​
684Use `queryKey` when the query contains opaque runtime logic that DB cannot
685stably represent:
686​
687```tsx
688function SearchTodos({ search }: { search: string }) {
689 return useLiveQuery({
690 queryKey: [todoCollection.id, 'search', search],
691 query: (q) =>
692 q
693 .from({ todo: todoCollection })
694 .fn.where(({ todo }) =>
695 todo.title.toLowerCase().includes(search.toLowerCase())
696 ),
697 })
699```
700​
701Common reasons to add `queryKey`:
702​
703- `.fn.where(...)`
704- `.fn.select(...)`
705- `.fn.having(...)`
706- function values, symbols, class instances, or circular objects captured inside
707 the structured query
708- a render path where derived identity becomes measurably expensive
709​
710When structured IR cannot be hashed and the query has no `queryKey`, a hook
711that compares identity throws `UnhashableQueryIRError`: React and Preact hooks,
712and any hook backed by a `DbClient`, which matches queries by identity hash. An
713empty `queryKey` counts as none. Represent the values that opaque logic
714captures in `queryKey`, so the query recompiles when they change.
715​
716DB also warns once in development if deriving identity becomes expensive enough
717that an explicit `queryKey` would be better.
718​
719Use the config object form:
720​
721```tsx
722useLiveQuery({
723 query: (q) => q.from({ todo: todoCollection }),
724})
725```
726​
727Add `queryKey` only if the query uses opaque logic or trips the performance
728warning.
729​
730## Migration Guide
731​
732This section shows how to adopt SSR from standalone Collections. If your app
733already uses `DbClient`, keep that setup and apply the
734[RC migration changes](./migrate-to-1-0-rc.md), including hook dependency arrays
735and explicit server preparation.
736​
737### 1. Create descriptors instead of SSR singletons
738​
739For collections that need SSR, replace module-level `createCollection(...)`
740with a reusable `collectionOptions(...)` descriptor.
741​
742```tsx
743// Before
744export const todoCollection = createCollection({
745 id: 'todos',
746 getKey: (todo) => todo.id,
747 sync: todoSync,
748})
749​
750// After
751export const todoCollection = collectionOptions('todos', () => ({
752 id: 'todos',
753 getKey: (todo: Todo) => todo.id,
754 sync: createTodoSync(),
755}))
756```
757​
758Put mutable state and closures inside the factory. First-party adapter option
759creators can also be passed directly because they provide a fresh config
760factory. Collections that never participate in SSR can keep using
761`createCollection`.
762​
763### 2. Add a `DbClient`
764​
765Use a new client for every server request and a stable client for each browser
766app instance.
767​
768```tsx
769const dbClient = new DbClient()
770```
771​
772In tests, create a new client per test unless the test is explicitly covering
773shared state.
774​
775### 3. Wrap React with `DbProvider`
776​
777```tsx
778root.render(
779 <DbProvider client={dbClient}>
780 <App />
781 </DbProvider>
783```
784​
785Hooks that resolve collection descriptors need this provider. Without it, DB
786throws instead of falling back to hidden global state.
787​
788### 4. Use collection hooks for imperative operations
789​
790Use descriptors directly in live query sources, and materialize only when you
791need collection methods:
792​
793```tsx
794function useTodoCollection() {
795 return useDbClient().collection(todoCollection)
797​
798function TodoActions({ id }: { id: string }) {
799 const todos = useTodoCollection()
800​
801 return (
802 <button onClick={() => todos.delete(id)}>
803 Delete
804 </button>
805 )
807```
808​
809This keeps request/client scoping in one place and avoids reintroducing
810module-level collections.
811​
812### 5. Replace dependency arrays
813​
814Most queries can drop the dependency array entirely:
815​
816```tsx
817// Before
818useLiveQuery(
819 (q) =>
820 q
821 .from({ todo: todoCollection })
822 .where(({ todo }) => eq(todo.status, status)),
823 // @ts-expect-error Dependency arrays are removed in the RC.
824 [status],
826​
827// After
828useLiveQuery({
829 query: (q) =>
830 q
831 .from({ todo: todoCollection })
832 .where(({ todo }) => eq(todo.status, status)),
833})
834```
835​
836If the query uses opaque functional variants, add `queryKey`:
837​
838```tsx
839useLiveQuery({
840 queryKey: [todoCollection.id, 'status-fn', status],
841 query: (q) =>
842 q
843 .from({ todo: todoCollection })
844 .fn.where(({ todo }) => todo.status === status),
845})
846```
847​
848### 6. Preload and dehydrate on the server
849​
850Preload a collection when the browser should receive normalized source rows:
851​
852```tsx
853const dbClient = new DbClient()
854const todos = dbClient.collection(todoCollection)
855await todos.preload()
856​
857return {
858 dbState: dbClient.dehydrate(),
860```
861​
862Preload a live query when the browser only needs the rendered result:
863​
864```tsx
865const dbClient = new DbClient()
866await dbClient.preloadLiveQuery({ query: openTodosQuery })
867​
868return {
869 dbState: dbClient.dehydrate(),
871```
872​
873### 7. Hydrate before client hooks read DB
874​
875```tsx
876<DbProvider client={client}>
877 <HydrationBoundary state={loaderData.dbState}>
878 <App />
879 </HydrationBoundary>
880</DbProvider>
881```
882​
883Imperative integrations can call `client.hydrate(loaderData.dbState)` before
884rendering instead.
885​
886## Compatibility
887​
888The SSR APIs remain available in the first 1.0 RC. React dependency-array hook forms have been removed.
889​
890Still supported:
891​
892- `createCollection(...)`
893- passing collection instances to `useLiveQuery(...)`
894- mutation APIs such as `insert`, `update`, `delete`, `subscribe`, and
895 optimistic mutation helpers
896​
897Query identity checks:
898​
899- React hooks use derived query identity or an explicit, nonempty `queryKey`.
900- Opaque query IR without a nonempty `queryKey` throws
901 `UnhashableQueryIRError` in a hook that compares identity (React, Preact, or
902 any `DbClient`-backed hook).
903- Expensive derived identity warns in development and suggests `queryKey`.
904​
905Opaque query IR without a serializable `queryKey` throws when React cannot
906derive a stable identity.
907​
908Required for SSR:
909​
910- stable explicit collection ids
911- request-scoped server `DbClient`
912- browser-scoped client `DbClient`
913- `DbProvider` for descriptor resolution in React
914- `dehydrate()` on the server and `hydrate()` in the browser
915​
916Required for render-time Suspense streaming:
917​
918- `routerWithDbClient(router, dbClient)`
919- `useLiveSuspenseQuery(...)` inside a Suspense boundary
920- a stable derived query identity or explicit serializable `queryKey`
921​
922## SSR Introduction Changelog
923​
924This section records the original SSR feature release. Its React dependency
925array deprecation was completed in the first 1.0 RC.
926​
927### Added
928​
929- `DbClient`
930- `collectionOptions(...)`
931- `CollectionOptions` descriptor type
932- `CollectionMaterializeOptions`
933- `DehydratedDbState`
934- `DehydratedCollectionChunk`
935- `DehydratedCollectionRow`
936- `dbClient.collection(descriptor, options?)`
937- `dbClient.dehydrate()`
938- `dbClient.hydrate(state)`
939- `dbClient.applyCollectionChunk(chunk)`
940- `dbClient.subscribe(listener)`
941- `dbClient.createTransaction(config)`
942- `dbClient.cleanup()`
943- React `DbProvider`
944- React `useDbClient()`
945- React `useOptionalDbClient()`
946- React `HydrationBoundary`
947- React descriptor resolution inside live query builders
948- React derived structured query identity
949- React `queryKey` escape hatch for opaque or hot-path queries
950- React per-query `client` override
951- SSR-capable `useSyncExternalStore` server snapshot support
952- `dbClient.preloadLiveQuery(...)`
953- Svelte `DbProvider`, `useDbClient()`, descriptor resolution, and synchronous
954 server snapshot support
955- TanStack Start and Next.js Playwright SSR E2E coverage
956- `@tanstack/react-router-with-db`
957- render-time `useLiveSuspenseQuery` promise streaming
958​
959### Changed
960​
961- React `useLiveQuery({ query })` can use collection descriptors directly in
962 `from`, `join`, `leftJoin`, and `unionAll` sources when a `DbProvider` is
963 present.
964- React live query identity is derived from normalized structured IR when no
965 explicit `queryKey` is supplied.
966- Explicit collection preloading serializes normalized collection rows.
967- Live-query preloading and render-time discovery serialize ordered result
968 snapshots without implicitly serializing source collections.
969- Browser observers keep the hydrated result visible while normal source sync
970 starts, then publish one authoritative handoff.
971- Hydration applies rows as committed synced state without invoking mutation
972 handlers or creating optimistic state.
973- Hydration and adapter sync begin in a deterministic order: pending rows and
974 sync metadata are imported before sync starts.
975- `DbClient` owns collection instances and ambient transaction scope; cleanup
976 releases both.
977- Incremental chunks use the same collection payload shape as full dehydration.
978- Streamed live-query promises resolve to live-query result snapshots.
979​
980### Since Removed
981​
982- React dependency arrays for `useLiveQuery` and wrappers that delegate to it.
983 They were removed in the first 1.0 RC.
984​
985### Not Changed
986​
987- `createCollection(...)` remains available.
988- Direct collection runtime APIs remain available.
989- Vue, Solid, and Angular keep their existing dependency/reactivity model until
990 they get their own SSR/client-provider work. Svelte is covered by this change.
991- Query collection `queryKey` is still TanStack Query's cache key. It is
992 separate from React live query identity.
993​
994## Validation
995​
996The SSR strategy is covered by:
997​
998- core `DbClient` tests for hydration, streaming chunks, sync metadata,
999 initial data precedence, explicit ids, and no optimistic serialization
1000- React tests for `DbProvider`, descriptor resolution, derived query identity,
1001 `queryKey`, derived-identity performance warnings, SSR result snapshots, and
1002 atomic handoff
1003- Svelte tests for provider ownership, server snapshot rendering, and browser
1004 handoff
1005- query adapter tests to ensure Query cache behavior still holds
1006- persistence core tests to ensure persisted row behavior remains intact
1007- TanStack Start and Next.js Playwright E2Es that verify a Suspense fallback,
1008 streamed query result, omitted source-only data, clean hydration, and atomic
1009 replacement by browser sync