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

ssr.md

875 lines26.4 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​
35Existing apps continue to work. `createCollection(...)` and direct collection
36instances still exist. The migration is required when you want SSR-safe request
37isolation, hydration, incremental chunks, Suspense streaming, or the 1.0-ready
38React hook shape.
39​
40The old dependency-array form now warns:
41​
42```tsx
43useLiveQuery((q) => q.from({ todos }).where(...), [status])
44```
45​
46It still works, but warns in development and will be removed in 1.0. Prefer:
47​
48```tsx
49useLiveQuery({
50 query: (q) => q.from({ todos: todoCollection }).where(...),
51})
52```
53​
54React derives live query identity from structured query IR by default. Add
55`queryKey` only for opaque functional query logic or for a hot render path where
56you want to skip derived identity work.
57​
58If the old dependency array tracked a Collection object that you replace while
59the hook stays mounted, give the replacement a distinct ID. A different source
60object with the same ID now throws in the derived-identity form. To reuse the
61ID, unmount the old hook, clean up its source and client scope, then mount the
62replacement.
63​
64## Cheat Sheet
65​
66| Task | Before | SSR-friendly |
67| --- | --- | --- |
68| Define a collection | `createCollection(options)` | `collectionOptions(id, factory)` |
69| Materialize a collection | module-level singleton | `dbClient.collection(todoCollection)` |
70| Scope collection state | module lifetime | `new DbClient()` per request/browser/test |
71| Provide React context | none | `<DbProvider client={dbClient}>` |
72| Query from React | direct collection instance | descriptor in `from`, resolved by `DbProvider` |
73| Mutate from React | import singleton collection | `useDbClient().collection(todoCollection)` |
74| Server preload | ad hoc collection preload | `collection.preload()` or `dbClient.preloadLiveQuery(...)` |
75| Serialize SSR state | none | `const state = dbClient.dehydrate()` |
76| Hydrate in browser | none | `dbClient.hydrate(state)` before hooks read it |
77| Apply rows incrementally | custom app state | `dbClient.applyCollectionChunk(chunk)` |
78| Stream render-time results | none | `routerWithDbClient(router, dbClient)` |
79| React query identity | dependency array | derived IR, or `queryKey` when needed |
80​
81Building or extending a Query keeps descriptors in its plan without starting
82their source Collections. The client-aware hook or `dbClient.preloadLiveQuery()`
83binds the finished plan when it consumes it. Reuse the original unbound Query
84across clients; a prepared Query contains Collections from the client that
85prepared it.
86​
87### Minimal React Pattern
88​
89```tsx
90import {
91 DbClient,
92 DbProvider,
93 Query,
94 collectionOptions,
95 eq,
96 useDbClient,
97 useLiveQuery,
98} from '@tanstack/react-db'
99​
100const todoCollection = collectionOptions('todos', () => ({
101 id: 'todos',
102 getKey: (todo: Todo) => todo.id,
103 sync: {
104 sync: ({ markReady }) => {
105 markReady()
106 },
107 },
108}))
109​
110function useTodoCollection() {
111 return useDbClient().collection(todoCollection)
113​
114function Todos({ status }: { status: string }) {
115 const todos = useTodoCollection()
116​
117 const { data } = useLiveQuery({
118 query: (q) =>
119 q
120 .from({ todo: todoCollection })
121 .where(({ todo }) => eq(todo.status, status)),
122 })
123​
124 return (
125 <ul>
126 {data.map((todo) => (
127 <li
128 key={todo.id}
129 onClick={() => todos.update(todo.id, (draft) => {
130 draft.done = true
131 })}
132 >
133 {todo.title}
134 </li>
135 ))}
136 </ul>
137 )
139​
140const dbClient = new DbClient()
141​
142root.render(
143 <DbProvider client={dbClient}>
144 <Todos status="open" />
145 </DbProvider>
147```
148​
149A descriptor query can also be defined outside React, without a `DbClient` at
150definition time:
151​
152```tsx
153const openTodosQuery = new Query()
154 .from({ todo: todoCollection })
155 .where(({ todo }) => eq(todo.status, 'open'))
156​
157function OpenTodos() {
158 const { data } = useLiveQuery({ query: openTodosQuery })
159 return <span>{data.length} open todos</span>
161```
162​
163The consuming hook binds this query to its `DbProvider` client. The same query
164can be used with `dbClient.preloadLiveQuery({ query: openTodosQuery })` on the
165server, or under another provider with a different client. For that reuse, the
166descriptor must have a reusable factory. Executing a descriptor query without
167a client throws when the source Collection is needed.
168​
169The factory matters when config contains mutable adapter state or closures.
170Every `DbClient` gets a fresh config and collection instance. First-party
171adapter option creators already attach an equivalent factory, so this is also
172safe:
173​
174```tsx
175const todoCollection = collectionOptions(
176 localOnlyCollectionOptions<Todo>({
177 id: 'todos',
178 getKey: (todo) => todo.id,
179 })
181```
182​
183Within one `DbClient`, descriptors with the same `id` resolve to the same
184collection. Only the first descriptor is materialized. Include every dynamic
185parameter that changes the collection in its `id`.
186​
187A descriptor created from an arbitrary concrete config can be materialized by
188one `DbClient` only. Use the explicit factory form for custom adapters and
189request-scoped dependencies.
190​
191## SSR Flow
192​
193The server and browser use the same descriptors, but different `DbClient`
194instances.
195​
196```txt
197server request
198 -> new DbClient()
199 -> preload an explicit collection or live-query result
200 -> dbClient.dehydrate()
201 -> send state through framework loader
202​
203browser
204 -> new DbClient()
205 -> dbClient.hydrate(loaderState)
206 -> <DbProvider client={dbClient}>
207 -> useLiveQuery({ query })
208 -> start source sync
209 -> atomically replace any query snapshot with the live result
210```
211​
212During React hydration, descriptor-backed queries read either hydrated
213collection rows or their matching query-result snapshot for the first browser
214render. Adapter sync and queued on-demand loads start when React commits the
215external-store subscription, so the initial markup still matches the server.
216The snapshot remains visible while the source is loading. Once the browser live
217query is ready, DB publishes one handoff from the snapshot to the live result.
218​
219A hydrated query hash identifies a portable result, but the payload does not
220contain the server's Collection objects. The first browser hook that commits a
221subscription, or the first browser `preloadLiveQuery()` call, claims the local
222source Collections for that reusable result. While the result is pending or
223successful, later local consumers with the same hash must use those Collection
224objects in the same query positions. A different source object with the same ID
225is rejected; give a genuinely different query a distinct `queryKey`. A newer
226hydration chunk updates the result without changing its established claim.
227`useLiveSuspenseQuery` can preload during render, claiming a source even if
228React never commits that render. A failed stream releases its claim, so a newer
229hydrated result can accept the first healthy local source. Once a subscribed
230live result becomes authoritative, the client consumes the stream;
231a later observer uses its own source Collection, even under the same hash.
232​
233### Server
234​
235Create a fresh `DbClient` for each request. Materialize descriptors through that
236client, preload the data needed for the route, and dehydrate the client.
237​
238```tsx
239import { DbClient, collectionOptions, eq } from '@tanstack/db'
240​
241export const todoCollection = collectionOptions('todos', () => ({
242 id: 'todos',
243 getKey: (todo: Todo) => todo.id,
244 syncMode: 'on-demand',
245 sync: {
246 sync: ({ markReady, begin, write, commit }) => {
247 markReady()
248​
249 return {
250 loadSubset: async () => {
251 const todos = await api.todos.list()
252 begin()
253 for (const todo of todos) {
254 write({ type: 'insert', value: todo })
255 }
256 commit()
257 return true
258 },
259 }
260 },
261 },
262}))
263​
264export async function loadTodosForSsr() {
265 const dbClient = new DbClient()
266 const todos = dbClient.collection(todoCollection)
267 await todos.preload()
268​
269 return dbClient.dehydrate()
271```
272​
273This explicit collection preload dehydrates normalized source rows. Use it when
274multiple browser queries need the same source data.
275​
276If the source is much larger than the rendered result, preload the query instead:
277​
278```tsx
279const dbClient = new DbClient()
280​
281await dbClient.preloadLiveQuery({
282 query: (q) =>
283 q
284 .from({ todo: todoCollection })
285 .where(({ todo }) => eq(todo.status, 'open'))
286 .select(({ todo }) => ({ id: todo.id, title: todo.title })),
287})
288​
289const state = dbClient.dehydrate()
290```
291​
292This payload contains the projected query result and no source collection rows
293unless that collection was also materialized explicitly.
294​
295### Browser
296​
297Hydrate the browser client before rendering components that read from DB.
298​
299```tsx
300import {
301 DbClient,
302 DbProvider,
303 HydrationBoundary,
304} from '@tanstack/react-db'
305​
306function App({ dehydratedDbState }: { dehydratedDbState: DehydratedDbState }) {
307 const [dbClient] = React.useState(() => new DbClient())
308​
309 return (
310 <DbProvider client={dbClient}>
311 <HydrationBoundary state={dehydratedDbState}>
312 <Routes />
313 </HydrationBoundary>
314 </DbProvider>
315 )
317```
318​
319Frameworks differ in how loader data reaches the client, but the DB handoff is
320the same: `DbClient` on the server, `dehydrate()`, then `hydrate()` into the
321browser client.
322​
323### Svelte
324​
325Svelte resolves descriptors from its own `DbProvider` and reads hydrated query
326snapshots synchronously during server rendering:
327​
328```svelte
329<script lang="ts">
330 import { DbClient, DbProvider } from '@tanstack/svelte-db'
331 import Todos from './Todos.svelte'
332​
333 const client = new DbClient()
334 client.hydrate(dehydratedDbState)
335</script>
336​
337<DbProvider {client}>
338 <Todos />
339</DbProvider>
340```
341​
342Inside `Todos.svelte`, `useLiveQuery({ query })` can use collection descriptors
343directly. The browser subscription starts source sync and performs the same
344snapshot-to-live-result handoff as React.
345​
346Live demo: https://tanstack-db-ssr-demo.netlify.app/ssr-db
347​
348## Suspense Streaming with TanStack Start
349​
350`@tanstack/react-router-with-db` follows the same integration pattern as
351`@tanstack/react-router-with-query`:
352​
353```tsx
354import { DbClient } from '@tanstack/react-db'
355import { createRouter } from '@tanstack/react-router'
356import { routerWithDbClient } from '@tanstack/react-router-with-db'
357​
358export type RouterContext = {
359 dbClient: DbClient
361​
362export function getRouter() {
363 const dbClient = new DbClient()
364 const router = createRouter({
365 routeTree,
366 context: { dbClient },
367 })
368​
369 return routerWithDbClient(router, dbClient)
371```
372​
373The adapter adds `dbClient` to router context, wraps the app in `DbProvider`,
374dehydrates critical state, and opens a stream for query results discovered later
375during rendering.
376​
377```tsx
378function RouteComponent() {
379 return (
380 <Suspense fallback={<p>Loading todos</p>}>
381 <TodoList />
382 </Suspense>
383 )
385​
386function TodoList() {
387 const { data } = useLiveSuspenseQuery({
388 query: (q) =>
389 q
390 .from({ todo: todoCollection })
391 .where(({ todo }) => eq(todo.status, 'open')),
392 })
393​
394 return data.map((todo) => <Todo key={todo.id} todo={todo} />)
396```
397​
398When `TodoList` suspends on the server, the adapter streams the pending query
399promise. That promise resolves to the ordered live-query result snapshot inside
400the streamed `DehydratedDbState`. The source collections and D2 graph do not
401cross the wire. The browser shows the snapshot, starts the source collections
402and live query normally, then replaces the snapshot when the browser result is
403ready.
404​
405The server and browser must derive the same live-query identity. Structured
406queries do this automatically. An opaque query must provide a serializable
407`queryKey`; render-time streaming throws if it cannot derive an identity.
408​
409## Suspense Streaming with Next.js
410​
411Next.js App Router can transport the same pending query promise through React
412Server Components. Start the preload without awaiting it, dehydrate the pending
413result, and pass that state to a client hydration boundary:
414​
415```tsx
416export default function Page() {
417 const dbClient = new DbClient()
418 void dbClient.preloadLiveQuery({ query: openTodosQuery })
419​
420 const state = dbClient.dehydrate({
421 shouldDehydrateCollection: () => false,
422 shouldDehydrateLiveQuery: () => true,
423 })
424​
425 return (
426 <DbHydration state={state}>
427 <Suspense fallback={<p>Loading todos</p>}>
428 <TodoList />
429 </Suspense>
430 </DbHydration>
431 )
433```
434​
435`DbHydration` is a client component that creates one browser `DbClient`, wraps
436children in `DbProvider`, and passes `state` to `HydrationBoundary`. React streams
437the promise result into that boundary. The full working integration is in
438`examples/react/next-ssr-e2e`.
439​
440## Incremental Collection Hydration
441​
442Applications can also apply collection rows received through their own stream.
443Incremental hydration uses the same collection chunk shape as holistic
444dehydration:
445​
446```ts
447dbClient.applyCollectionChunk({
448 collectionId: 'todos',
449 rows: [
450 {
451 key: 'todo-1',
452 value: {
453 id: 'todo-1',
454 title: 'Streamed row',
455 status: 'open',
456 },
457 metadata: { source: 'stream' },
458 },
459 ],
460 syncMeta: { version: 1, cursor: 'abc' },
461})
462```
463​
464If the target collection is already materialized, the rows apply immediately and
465existing live queries react from collection state. If the collection is not
466materialized yet, the chunk is stored and applied when that `collectionId`
467materializes.
468​
469## What Gets Serialized
470​
471`dbClient.dehydrate()` can emit two independent snapshot types.
472​
473Serialized:
474​
475- explicit collection snapshots: collection id, synced row keys and values, row
476 metadata, and adapter sync metadata from `exportSyncMeta`
477- live-query snapshots: query hash and ordered result rows; completed explicit
478 preloads are included by default, while framework integrations opt pending
479 promises into streaming
480​
481Not serialized:
482​
483- mutation handlers
484- pending optimistic mutations
485- pending subscriptions
486- D2 graphs or compiled pipelines
487- transaction stacks
488- module-level runtime state
489- source collection rows for a query-result snapshot, unless that collection was
490 also explicitly materialized for dehydration
491​
492Choose the payload unit according to what the browser needs. Explicit collection
493preloading preserves normalized rows for reuse across queries. Live-query
494preloading avoids shipping a 50-100x larger source when the rendered projection
495is small. Neither mode serializes executable query state.
496​
497## Sync Metadata
498​
499Adapters can participate in resumable sync with three optional hooks:
500​
501```ts
502type SyncConfig = {
503 exportSyncMeta?: () => unknown
504 importSyncMeta?: (meta: unknown) => void
505 mergeSyncMeta?: (current: unknown, incoming: unknown) => unknown
507```
508​
509The metadata shape is adapter-owned. Version it inside the adapter payload. If an
510adapter cannot understand incoming metadata, it should ignore it and restart
511sync from a safe point.
512​
513During hydration, DB imports `syncMeta` into the materialized collection. If the
514collection already has current metadata, DB calls `mergeSyncMeta(current,
515incoming)` when provided and imports the merged result.
516​
517If an adapter does not implement sync metadata hooks, row snapshots still hydrate
518and the adapter can restart sync normally.
519​
520## Initial Data
521​
522`initialData` is a startup seed, not a sync-ready signal.
523​
524Before adapter sync starts, current `DbClient` precedence from lowest to highest
525is:
526​
5271. per-materialization `initialData`
5282. persisted rows
5293. hydrated rows
530​
531Fresh adapter sync is authoritative over all three. Hydrated and initial rows
532are provisional base state, so the adapter's first insert for the same key is
533reconciled as an update instead of raising a duplicate-key error.
534​
535Hydrated rows and `initialData` never mark adapter sync as ready by themselves.
536The adapter still owns readiness through its sync lifecycle.
537​
538## React Query Identity
539​
540React hooks derive live query identity from structured query IR by default:
541​
542```tsx
543function Todos({ status }: { status: string }) {
544 return useLiveQuery({
545 query: (q) =>
546 q
547 .from({ todo: todoCollection })
548 .where(({ todo }) => eq(todo.status, status)),
549 })
551```
552​
553The captured `status` value is represented in the structured IR, so no
554dependency array or `queryKey` is required.
555​
556Use `queryKey` when the query contains opaque runtime logic that DB cannot
557stably represent:
558​
559```tsx
560function SearchTodos({ search }: { search: string }) {
561 return useLiveQuery({
562 queryKey: [todoCollection.id, 'search', search],
563 query: (q) =>
564 q
565 .from({ todo: todoCollection })
566 .fn.where(({ todo }) =>
567 todo.title.toLowerCase().includes(search.toLowerCase())
568 ),
569 })
571```
572​
573Common reasons to add `queryKey`:
574​
575- `.fn.where(...)`
576- `.fn.select(...)`
577- `.fn.having(...)`
578- function values, symbols, class instances, or circular objects captured inside
579 the structured query
580- a render path where derived identity becomes measurably expensive
581​
582Before 1.0, DB warns when structured IR cannot be hashed and preserves the
583legacy mount-stable identity. The query still works, but captured values inside
584opaque logic are not reactive unless they are represented in `queryKey`. In 1.0,
585an unhashable query without `queryKey` will throw.
586​
587DB also warns once in development if deriving identity becomes expensive enough
588that an explicit `queryKey` would be better.
589​
590Dependency arrays are accepted for backwards compatibility:
591​
592```tsx
593useLiveQuery((q) => q.from({ todo: todoCollection }), [status])
594```
595​
596They warn in development and will be removed in 1.0. Migrate to the config
597object form:
598​
599```tsx
600useLiveQuery({
601 query: (q) => q.from({ todo: todoCollection }),
602})
603```
604​
605Add `queryKey` only if the query uses opaque logic or trips the performance
606warning.
607​
608## Migration Guide
609​
610### 1. Create descriptors instead of SSR singletons
611​
612For collections that need SSR, replace module-level `createCollection(...)`
613with a reusable `collectionOptions(...)` descriptor.
614​
615```tsx
616// Before
617export const todoCollection = createCollection({
618 id: 'todos',
619 getKey: (todo) => todo.id,
620 sync: todoSync,
621})
622​
623// After
624export const todoCollection = collectionOptions('todos', () => ({
625 id: 'todos',
626 getKey: (todo: Todo) => todo.id,
627 sync: createTodoSync(),
628}))
629```
630​
631Put mutable state and closures inside the factory. First-party adapter option
632creators can also be passed directly because they provide a fresh config
633factory. Collections that never participate in SSR can keep using
634`createCollection`.
635​
636### 2. Add a `DbClient`
637​
638Use a new client for every server request and a stable client for each browser
639app instance.
640​
641```tsx
642const dbClient = new DbClient()
643```
644​
645In tests, create a new client per test unless the test is explicitly covering
646shared state.
647​
648### 3. Wrap React with `DbProvider`
649​
650```tsx
651root.render(
652 <DbProvider client={dbClient}>
653 <App />
654 </DbProvider>
656```
657​
658Hooks that resolve collection descriptors need this provider. Without it, DB
659throws instead of falling back to hidden global state.
660​
661### 4. Use collection hooks for imperative operations
662​
663Use descriptors directly in live query sources, and materialize only when you
664need collection methods:
665​
666```tsx
667function useTodoCollection() {
668 return useDbClient().collection(todoCollection)
670​
671function TodoActions({ id }: { id: string }) {
672 const todos = useTodoCollection()
673​
674 return (
675 <button onClick={() => todos.delete(id)}>
676 Delete
677 </button>
678 )
680```
681​
682This keeps request/client scoping in one place and avoids reintroducing
683module-level collections.
684​
685### 5. Replace dependency arrays
686​
687Most queries can drop the dependency array entirely:
688​
689```tsx
690// Before
691useLiveQuery(
692 (q) =>
693 q
694 .from({ todo: todoCollection })
695 .where(({ todo }) => eq(todo.status, status)),
696 [status],
698​
699// After
700useLiveQuery({
701 query: (q) =>
702 q
703 .from({ todo: todoCollection })
704 .where(({ todo }) => eq(todo.status, status)),
705})
706```
707​
708If the query uses opaque functional variants, add `queryKey`:
709​
710```tsx
711useLiveQuery({
712 queryKey: [todoCollection.id, 'status-fn', status],
713 query: (q) =>
714 q
715 .from({ todo: todoCollection })
716 .fn.where(({ todo }) => todo.status === status),
717})
718```
719​
720### 6. Preload and dehydrate on the server
721​
722Preload a collection when the browser should receive normalized source rows:
723​
724```tsx
725const dbClient = new DbClient()
726const todos = dbClient.collection(todoCollection)
727await todos.preload()
728​
729return {
730 dbState: dbClient.dehydrate(),
732```
733​
734Preload a live query when the browser only needs the rendered result:
735​
736```tsx
737const dbClient = new DbClient()
738await dbClient.preloadLiveQuery({ query: openTodosQuery })
739​
740return {
741 dbState: dbClient.dehydrate(),
743```
744​
745### 7. Hydrate before client hooks read DB
746​
747```tsx
748<DbProvider client={client}>
749 <HydrationBoundary state={loaderData.dbState}>
750 <App />
751 </HydrationBoundary>
752</DbProvider>
753```
754​
755Imperative integrations can call `client.hydrate(loaderData.dbState)` before
756rendering instead.
757​
758## Compatibility
759​
760No existing public API is removed by this change.
761​
762Still supported:
763​
764- `createCollection(...)`
765- passing collection instances to `useLiveQuery(...)`
766- `useLiveQuery(queryFn, deps)`
767- `useLiveSuspenseQuery(queryFn, deps)`
768- mutation APIs such as `insert`, `update`, `delete`, `subscribe`, and
769 optimistic mutation helpers
770​
771Warnings:
772​
773- React dependency arrays warn in development and will be removed in 1.0.
774- Opaque query IR without `queryKey` warns in development and keeps legacy
775 mount-stable identity until 1.0. In 1.0 it will throw.
776- Expensive derived identity warns in development and suggests `queryKey`.
777​
778Required for SSR:
779​
780- stable explicit collection ids
781- request-scoped server `DbClient`
782- browser-scoped client `DbClient`
783- `DbProvider` for descriptor resolution in React
784- `dehydrate()` on the server and `hydrate()` in the browser
785​
786Required for render-time Suspense streaming:
787​
788- `routerWithDbClient(router, dbClient)`
789- `useLiveSuspenseQuery(...)` inside a Suspense boundary
790- a stable derived query identity or explicit serializable `queryKey`
791​
792## Detailed Changelog
793​
794### Added
795​
796- `DbClient`
797- `collectionOptions(...)`
798- `CollectionOptions` descriptor type
799- `CollectionMaterializeOptions`
800- `DehydratedDbState`
801- `DehydratedCollectionChunk`
802- `DehydratedCollectionRow`
803- `dbClient.collection(descriptor, options?)`
804- `dbClient.dehydrate()`
805- `dbClient.hydrate(state)`
806- `dbClient.applyCollectionChunk(chunk)`
807- `dbClient.subscribe(listener)`
808- `dbClient.createTransaction(config)`
809- `dbClient.cleanup()`
810- React `DbProvider`
811- React `useDbClient()`
812- React `useOptionalDbClient()`
813- React `HydrationBoundary`
814- React descriptor resolution inside live query builders
815- React derived structured query identity
816- React `queryKey` escape hatch for opaque or hot-path queries
817- React per-query `client` override
818- SSR-capable `useSyncExternalStore` server snapshot support
819- `dbClient.preloadLiveQuery(...)`
820- Svelte `DbProvider`, `useDbClient()`, descriptor resolution, and synchronous
821 server snapshot support
822- TanStack Start and Next.js Playwright SSR E2E coverage
823- `@tanstack/react-router-with-db`
824- render-time `useLiveSuspenseQuery` promise streaming
825​
826### Changed
827​
828- React `useLiveQuery({ query })` can use collection descriptors directly in
829 `from`, `join`, `leftJoin`, and `unionAll` sources when a `DbProvider` is
830 present.
831- React live query identity is derived from normalized structured IR when no
832 explicit `queryKey` or legacy dependency array is supplied.
833- Explicit collection preloading serializes normalized collection rows.
834- Live-query preloading and render-time discovery serialize ordered result
835 snapshots without implicitly serializing source collections.
836- Browser observers keep the hydrated result visible while normal source sync
837 starts, then publish one authoritative handoff.
838- Hydration applies rows as committed synced state without invoking mutation
839 handlers or creating optimistic state.
840- Hydration and adapter sync begin in a deterministic order: pending rows and
841 sync metadata are imported before sync starts.
842- `DbClient` owns collection instances and ambient transaction scope; cleanup
843 releases both.
844- Incremental chunks use the same collection payload shape as full dehydration.
845- Streamed live-query promises resolve to live-query result snapshots.
846​
847### Deprecated
848​
849- React dependency arrays for `useLiveQuery` and wrappers that delegate to it.
850 They still work and warn in development. They are planned for removal in 1.0.
851​
852### Not Changed
853​
854- `createCollection(...)` remains available.
855- Direct collection runtime APIs remain available.
856- Vue, Solid, and Angular keep their existing dependency/reactivity model until
857 they get their own SSR/client-provider work. Svelte is covered by this change.
858- Query collection `queryKey` is still TanStack Query's cache key. It is
859 separate from React live query identity.
860​
861## Validation
862​
863The SSR strategy is covered by:
864​
865- core `DbClient` tests for hydration, streaming chunks, sync metadata,
866 initial data precedence, explicit ids, and no optimistic serialization
867- React tests for `DbProvider`, descriptor resolution, derived query identity,
868 `queryKey`, deprecation warnings, SSR result snapshots, and atomic handoff
869- Svelte tests for provider ownership, server snapshot rendering, and browser
870 handoff
871- query adapter tests to ensure Query cache behavior still holds
872- persistence core tests to ensure persisted row behavior remains intact
873- TanStack Start and Next.js Playwright E2Es that verify a Suspense fallback,
874 streamed query result, omitted source-only data, clean hydration, and atomic
875 replacement by browser sync