Open History to see the last commit
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)
112}
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 )
138}
139
140const dbClient = new DbClient()
141
142root.render(
143 <DbProvider client={dbClient}>
144 <Todos status="open" />
145 </DbProvider>
146)
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>
160}
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 })
180)
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()
270}
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
295Use the config object form in both the loader and the hook when they share a
296preloaded result:
297
298```tsx
299const openTodos = {
300 query: (q: InitialQueryBuilder) =>
301 q.from({ todo: todoCollection }).where(({ todo }) => eq(todo.status, 'open')),
302}
303
304await dbClient.preloadLiveQuery(openTodos)
305// In the component:
306const { data } = useLiveQuery(openTodos)
307```
308
309The function form `useLiveQuery(openTodos.query)` currently derives a different
310identity from `useLiveQuery(openTodos)`. It will not reuse the loader's result.
311Sharing the query callback alone is insufficient. To use an explicit `queryKey`,
312pass config objects with the same `queryKey` to both `preloadLiveQuery` and
313`useLiveQuery`. Their sources and result configuration must still describe the
314same query.
315
316### Prepare every server snapshot
317
318An ordinary server hook can render empty/loading state without a preload. To
319render data, await a matching `preloadLiveQuery()` or explicitly preload the
320source Collections. A different query warming the same source does not prepare
321this query's result for transport. Reading those incidental rows or their
322readiness during SSR throws an error with the required preparation steps.
323Normal browser reads and runtime query errors keep their usual behavior.
324
325Normalized source transport carries rows without query readiness. When a server
326hook reads explicitly prepared sources, it captures the query's render-time
327rows and status as a query result. Ready prepared queries can therefore finish
328non-streaming Suspense; loading queries remain loading. Later server writes and
329browser writes before hydration do not change that initial view. Browser commit
330starts acquisition and publishes the live status normally. A loading capture
331does not complete an explicit data preload.
332
333An ordinary hook can render loading before a Suspense sibling completes the
334same query. Each hook retains its own server-rendered view during hydration.
335The Router stream forwards a newer result for that query without replacing the
336ordinary hook's earlier view. A later boundary waits for its missing streamed
337result instead of substituting browser rows. DbClient retains transported server
338snapshots until cleanup, so one reader's commit cannot consume another
339boundary's initial view. New ordinary browser reads still use live results.
340
341Streaming `useLiveSuspenseQuery` discovers and prepares its result during render,
342including when another query already warmed the source. Ordinary hooks require
343explicit preparation to render that data. Opaque SSR queries require a serializable
344`queryKey`, including when the source is already warm.
345
346For `useLiveInfiniteQuery`, preload the initial window plus its one-row peek:
347
348```tsx
349const orderedTodos = new Query()
350 .from({ todo: todoCollection })
351 .orderBy(({ todo }) => todo.id)
352const pageSize = 20
353
354await dbClient.preloadLiveQuery({
355 query: orderedTodos.limit(pageSize + 1).offset(0),
356})
357// In the component:
358const result = useLiveInfiniteQuery(() => orderedTodos, { pageSize })
359```
360
361With an explicit `queryKey`, the DbClient query hash also includes limit and
362offset. Use the same initial window in the preload and the infinite hook.
363
364Custom dehydration filters must retain the query result that the markup requires.
365
366### Indexes before query compilation
367
368Create manual indexes when initializing each request or browser client, before
369preloading or rendering queries that use them:
370
371```tsx
372import { BasicIndex, DbClient, type CollectionOptions } from '@tanstack/db'
373
374function createDbClient(todoCollection: CollectionOptions<{ id: string }>) {
375 const client = new DbClient()
376 client.collection(todoCollection).createIndex((todo) => todo.id, {
377 indexType: BasicIndex,
378 })
379 return client
380}
381```
382
383Collection materialization does not start sync unless its config requests it.
384An index installed inside the sync callback can arrive after the ordered query
385has compiled. `autoIndex: 'eager'` with `defaultIndexType: BasicIndex` is an
386alternative when indexes should be created as queries compile. Descriptors
387currently have no `indexes` or `onCreate` option.
388
389### Preload lifetime
390
391`preloadLiveQuery()` has no built-in deadline or `AbortSignal` option. A source
392that keeps retrying without becoming ready can keep its preload pending. Apply
393an application deadline to request work and clean up its request-scoped client
394when abandoning it; a timer race alone does not stop the underlying sync.
395
396Preloaded results belong to the client. There is no public method to release
397one preloaded query. `cleanup()` releases the entire client and its Collections.
398Avoid accumulating route-specific preloads in a browser client without an
399application lifetime policy. A separately owned `createLiveQueryCollection()`
400can be preloaded and cleaned up explicitly when per-query ownership is needed.
401
402### Browser
403
404Hydrate the browser client before rendering components that read from DB.
405
406```tsx
407import {
408 DbClient,
409 DbProvider,
410 HydrationBoundary,
411} from '@tanstack/react-db'
412
413function App({ dehydratedDbState }: { dehydratedDbState: DehydratedDbState }) {
414 const [dbClient] = React.useState(() => new DbClient())
415
416 return (
417 <DbProvider client={dbClient}>
418 <HydrationBoundary state={dehydratedDbState}>
419 <Routes />
420 </HydrationBoundary>
421 </DbProvider>
422 )
423}
424```
425
426Frameworks differ in how loader data reaches the client, but the DB handoff is
427the same: `DbClient` on the server, `dehydrate()`, then `hydrate()` into the
428browser client.
429
430### Svelte
431
432Svelte resolves descriptors from its own `DbProvider` and reads hydrated query
433snapshots synchronously during server rendering:
434
435```svelte
436<script lang="ts">
437 import { DbClient, DbProvider } from '@tanstack/svelte-db'
438 import Todos from './Todos.svelte'
439
440 const client = new DbClient()
441 client.hydrate(dehydratedDbState)
442</script>
443
444<DbProvider {client} hydrating>
445 <Todos />
446</DbProvider>
447```
448
449Inside `Todos.svelte`, `useLiveQuery({ query })` can use collection descriptors
450directly. The browser subscription starts source sync and performs the same
451snapshot-to-live-result handoff as React.
452
453Set `hydrating` for each root initialized with Svelte's `hydrate()`. It preserves
454that root's server public snapshot even after another root publishes browser
455rows. Nested providers inherit it unless they specify another value. The
456provider clears it after mount, so later children read live rows. Omit it for
457ordinary `mount()` calls.
458
459Hooks that pass `client` explicitly also need a marked provider around their
460hydrated subtree. The client alone cannot identify hydration versus a fresh mount.
461
462Live demo: https://tanstack-db-ssr-demo.netlify.app/ssr-db
463
464## Suspense Streaming with TanStack Start
465
466`@tanstack/react-router-with-db` follows the same integration pattern as
467`@tanstack/react-router-with-query`:
468
469```tsx
470import { DbClient } from '@tanstack/react-db'
471import { createRouter } from '@tanstack/react-router'
472import { routerWithDbClient } from '@tanstack/react-router-with-db'
473
474export type RouterContext = {
475 dbClient: DbClient
476}
477
478export function getRouter() {
479 const dbClient = new DbClient()
480 const router = createRouter({
481 routeTree,
482 context: { dbClient },
483 })
484
485 return routerWithDbClient(router, dbClient)
486}
487```
488
489The adapter adds `dbClient` to router context, wraps the app in `DbProvider`,
490dehydrates critical state, and opens a stream for query results discovered later
491during rendering.
492
493```tsx
494function RouteComponent() {
495 return (
496 <Suspense fallback={<p>Loading todos</p>}>
497 <TodoList />
498 </Suspense>
499 )
500}
501
502function TodoList() {
503 const { data } = useLiveSuspenseQuery({
504 query: (q) =>
505 q
506 .from({ todo: todoCollection })
507 .where(({ todo }) => eq(todo.status, 'open')),
508 })
509
510 return data.map((todo) => <Todo key={todo.id} todo={todo} />)
511}
512```
513
514When `TodoList` suspends on the server, the adapter streams the pending query
515promise. That promise resolves to the ordered live-query result snapshot inside
516the streamed `DehydratedDbState`. The source collections and D2 graph do not
517cross the wire. The browser shows the snapshot, starts the source collections
518and live query normally, then replaces the snapshot when the browser result is
519ready.
520
521The server and browser must derive the same live-query identity. Structured
522queries do this automatically. An opaque query must provide a serializable
523`queryKey`; render-time streaming throws if it cannot derive an identity.
524
525## Suspense Streaming with Next.js
526
527Next.js App Router can transport the same pending query promise through React
528Server Components. Start the preload without awaiting it, dehydrate the pending
529result, and pass that state to a client hydration boundary:
530
531```tsx
532export default function Page() {
533 const dbClient = new DbClient()
534 void dbClient.preloadLiveQuery({ query: openTodosQuery })
535
536 const state = dbClient.dehydrate({
537 shouldDehydrateCollection: () => false,
538 shouldDehydrateLiveQuery: () => true,
539 })
540
541 return (
542 <DbHydration state={state}>
543 <Suspense fallback={<p>Loading todos</p>}>
544 <TodoList />
545 </Suspense>
546 </DbHydration>
547 )
548}
549```
550
551`DbHydration` is a client component that creates one browser `DbClient`, wraps
552children in `DbProvider`, and passes `state` to `HydrationBoundary`. React streams
553the promise result into that boundary. The full working integration is in
554`examples/react/next-ssr-e2e`.
555
556## Incremental Collection Hydration
557
558Applications can also apply collection rows received through their own stream.
559Incremental hydration uses the same collection chunk shape as holistic
560dehydration:
561
562```ts
563dbClient.applyCollectionChunk({
564 collectionId: 'todos',
565 rows: [
566 {
567 key: 'todo-1',
568 value: {
569 id: 'todo-1',
570 title: 'Streamed row',
571 status: 'open',
572 },
573 metadata: { source: 'stream' },
574 },
575 ],
576 syncMeta: { version: 1, cursor: 'abc' },
577})
578```
579
580If the target collection is already materialized, the rows apply immediately and
581existing live queries react from collection state. If the collection is not
582materialized yet, the chunk is stored and applied when that `collectionId`
583materializes.
584
585## What Gets Serialized
586
587`dbClient.dehydrate()` can emit two independent snapshot types.
588
589Serialized:
590
591- explicit collection snapshots: collection id, synced row keys and values, row
592 metadata, and adapter sync metadata from `exportSyncMeta`
593- live-query snapshots: query hash and ordered result rows; completed explicit
594 preloads are included by default, while framework integrations opt pending
595 promises into streaming
596
597Not serialized:
598
599- mutation handlers
600- pending optimistic mutations
601- pending subscriptions
602- D2 graphs or compiled pipelines
603- transaction stacks
604- module-level runtime state
605- source collection rows for a query-result snapshot, unless that collection was
606 also explicitly materialized for dehydration
607
608Choose the payload unit according to what the browser needs. Explicit collection
609preloading preserves normalized rows for reuse across queries. Live-query
610preloading avoids shipping a 50-100x larger source when the rendered projection
611is small. Neither mode serializes executable query state.
612
613## Sync Metadata
614
615Adapters can participate in resumable sync with three optional hooks:
616
617```ts
618type SyncConfig = {
619 exportSyncMeta?: () => unknown
620 importSyncMeta?: (meta: unknown) => void
621 mergeSyncMeta?: (current: unknown, incoming: unknown) => unknown
622}
623```
624
625The metadata shape is adapter-owned. Version it inside the adapter payload. If an
626adapter cannot understand incoming metadata, it should ignore it and restart
627sync from a safe point.
628
629During hydration, DB imports `syncMeta` into the materialized collection. If the
630collection already has current metadata, DB calls `mergeSyncMeta(current,
631incoming)` when provided and imports the merged result.
632
633If an adapter does not implement sync metadata hooks, row snapshots still hydrate
634and the adapter can restart sync normally.
635
636## Initial Data
637
638`initialData` is a startup seed, not a sync-ready signal.
639
640Before adapter sync starts, current `DbClient` precedence from lowest to highest
641is:
642
6431. per-materialization `initialData`
6442. persisted rows
6453. hydrated rows
646
647Fresh adapter sync is authoritative over all three. Hydrated and initial rows
648are provisional base state, so the adapter's first insert for the same key is
649reconciled as an update instead of raising a duplicate-key error.
650
651Hydrated rows and `initialData` never mark adapter sync as ready by themselves.
652The adapter still owns readiness through its sync lifecycle.
653
654## React Query Identity
655
656React hooks derive live query identity from structured query IR by default:
657
658```tsx
659function Todos({ status }: { status: string }) {
660 return useLiveQuery({
661 query: (q) =>
662 q
663 .from({ todo: todoCollection })
664 .where(({ todo }) => eq(todo.status, status)),
665 })
666}
667```
668
669The captured `status` value is represented in the structured IR, so no
670dependency array or `queryKey` is required.
671
672Use `queryKey` when the query contains opaque runtime logic that DB cannot
673stably represent:
674
675```tsx
676function SearchTodos({ search }: { search: string }) {
677 return useLiveQuery({
678 queryKey: [todoCollection.id, 'search', search],
679 query: (q) =>
680 q
681 .from({ todo: todoCollection })
682 .fn.where(({ todo }) =>
683 todo.title.toLowerCase().includes(search.toLowerCase())
684 ),
685 })
686}
687```
688
689Common reasons to add `queryKey`:
690
691- `.fn.where(...)`
692- `.fn.select(...)`
693- `.fn.having(...)`
694- function values, symbols, class instances, or circular objects captured inside
695 the structured query
696- a render path where derived identity becomes measurably expensive
697
698When structured IR cannot be hashed and the query has no `queryKey`, a hook
699that compares identity throws `UnhashableQueryIRError`: React and Preact hooks,
700and any hook backed by a `DbClient`, which matches queries by identity hash. An
701empty `queryKey` counts as none. Represent the values that opaque logic
702captures in `queryKey`, so the query recompiles when they change.
703
704DB also warns once in development if deriving identity becomes expensive enough
705that an explicit `queryKey` would be better.
706
707Dependency arrays are accepted for backwards compatibility:
708
709```tsx
710useLiveQuery((q) => q.from({ todo: todoCollection }), [status])
711```
712
713They warn in development and will be removed in 1.0. Migrate to the config
714object form:
715
716```tsx
717useLiveQuery({
718 query: (q) => q.from({ todo: todoCollection }),
719})
720```
721
722Add `queryKey` only if the query uses opaque logic or trips the performance
723warning.
724
725## Migration Guide
726
727### 1. Create descriptors instead of SSR singletons
728
729For collections that need SSR, replace module-level `createCollection(...)`
730with a reusable `collectionOptions(...)` descriptor.
731
732```tsx
733// Before
734export const todoCollection = createCollection({
735 id: 'todos',
736 getKey: (todo) => todo.id,
737 sync: todoSync,
738})
739
740// After
741export const todoCollection = collectionOptions('todos', () => ({
742 id: 'todos',
743 getKey: (todo: Todo) => todo.id,
744 sync: createTodoSync(),
745}))
746```
747
748Put mutable state and closures inside the factory. First-party adapter option
749creators can also be passed directly because they provide a fresh config
750factory. Collections that never participate in SSR can keep using
751`createCollection`.
752
753### 2. Add a `DbClient`
754
755Use a new client for every server request and a stable client for each browser
756app instance.
757
758```tsx
759const dbClient = new DbClient()
760```
761
762In tests, create a new client per test unless the test is explicitly covering
763shared state.
764
765### 3. Wrap React with `DbProvider`
766
767```tsx
768root.render(
769 <DbProvider client={dbClient}>
770 <App />
771 </DbProvider>
772)
773```
774
775Hooks that resolve collection descriptors need this provider. Without it, DB
776throws instead of falling back to hidden global state.
777
778### 4. Use collection hooks for imperative operations
779
780Use descriptors directly in live query sources, and materialize only when you
781need collection methods:
782
783```tsx
784function useTodoCollection() {
785 return useDbClient().collection(todoCollection)
786}
787
788function TodoActions({ id }: { id: string }) {
789 const todos = useTodoCollection()
790
791 return (
792 <button onClick={() => todos.delete(id)}>
793 Delete
794 </button>
795 )
796}
797```
798
799This keeps request/client scoping in one place and avoids reintroducing
800module-level collections.
801
802### 5. Replace dependency arrays
803
804Most queries can drop the dependency array entirely:
805
806```tsx
807// Before
808useLiveQuery(
809 (q) =>
810 q
811 .from({ todo: todoCollection })
812 .where(({ todo }) => eq(todo.status, status)),
813 [status],
814)
815
816// After
817useLiveQuery({
818 query: (q) =>
819 q
820 .from({ todo: todoCollection })
821 .where(({ todo }) => eq(todo.status, status)),
822})
823```
824
825If the query uses opaque functional variants, add `queryKey`:
826
827```tsx
828useLiveQuery({
829 queryKey: [todoCollection.id, 'status-fn', status],
830 query: (q) =>
831 q
832 .from({ todo: todoCollection })
833 .fn.where(({ todo }) => todo.status === status),
834})
835```
836
837### 6. Preload and dehydrate on the server
838
839Preload a collection when the browser should receive normalized source rows:
840
841```tsx
842const dbClient = new DbClient()
843const todos = dbClient.collection(todoCollection)
844await todos.preload()
845
846return {
847 dbState: dbClient.dehydrate(),
848}
849```
850
851Preload a live query when the browser only needs the rendered result:
852
853```tsx
854const dbClient = new DbClient()
855await dbClient.preloadLiveQuery({ query: openTodosQuery })
856
857return {
858 dbState: dbClient.dehydrate(),
859}
860```
861
862### 7. Hydrate before client hooks read DB
863
864```tsx
865<DbProvider client={client}>
866 <HydrationBoundary state={loaderData.dbState}>
867 <App />
868 </HydrationBoundary>
869</DbProvider>
870```
871
872Imperative integrations can call `client.hydrate(loaderData.dbState)` before
873rendering instead.
874
875## Compatibility
876
877No existing public API is removed by this change.
878
879Still supported:
880
881- `createCollection(...)`
882- passing collection instances to `useLiveQuery(...)`
883- `useLiveQuery(queryFn, deps)`
884- `useLiveSuspenseQuery(queryFn, deps)`
885- mutation APIs such as `insert`, `update`, `delete`, `subscribe`, and
886 optimistic mutation helpers
887
888Warnings:
889
890- React dependency arrays warn in development and will be removed in 1.0.
891- Opaque query IR without `queryKey` throws `UnhashableQueryIRError` in a
892 hook that compares identity (React, Preact, or any `DbClient`-backed hook).
893- Expensive derived identity warns in development and suggests `queryKey`.
894
895Required for SSR:
896
897- stable explicit collection ids
898- request-scoped server `DbClient`
899- browser-scoped client `DbClient`
900- `DbProvider` for descriptor resolution in React
901- `dehydrate()` on the server and `hydrate()` in the browser
902
903Required for render-time Suspense streaming:
904
905- `routerWithDbClient(router, dbClient)`
906- `useLiveSuspenseQuery(...)` inside a Suspense boundary
907- a stable derived query identity or explicit serializable `queryKey`
908
909## Detailed Changelog
910
911### Added
912
913- `DbClient`
914- `collectionOptions(...)`
915- `CollectionOptions` descriptor type
916- `CollectionMaterializeOptions`
917- `DehydratedDbState`
918- `DehydratedCollectionChunk`
919- `DehydratedCollectionRow`
920- `dbClient.collection(descriptor, options?)`
921- `dbClient.dehydrate()`
922- `dbClient.hydrate(state)`
923- `dbClient.applyCollectionChunk(chunk)`
924- `dbClient.subscribe(listener)`
925- `dbClient.createTransaction(config)`
926- `dbClient.cleanup()`
927- React `DbProvider`
928- React `useDbClient()`
929- React `useOptionalDbClient()`
930- React `HydrationBoundary`
931- React descriptor resolution inside live query builders
932- React derived structured query identity
933- React `queryKey` escape hatch for opaque or hot-path queries
934- React per-query `client` override
935- SSR-capable `useSyncExternalStore` server snapshot support
936- `dbClient.preloadLiveQuery(...)`
937- Svelte `DbProvider`, `useDbClient()`, descriptor resolution, and synchronous
938 server snapshot support
939- TanStack Start and Next.js Playwright SSR E2E coverage
940- `@tanstack/react-router-with-db`
941- render-time `useLiveSuspenseQuery` promise streaming
942
943### Changed
944
945- React `useLiveQuery({ query })` can use collection descriptors directly in
946 `from`, `join`, `leftJoin`, and `unionAll` sources when a `DbProvider` is
947 present.
948- React live query identity is derived from normalized structured IR when no
949 explicit `queryKey` or legacy dependency array is supplied.
950- Explicit collection preloading serializes normalized collection rows.
951- Live-query preloading and render-time discovery serialize ordered result
952 snapshots without implicitly serializing source collections.
953- Browser observers keep the hydrated result visible while normal source sync
954 starts, then publish one authoritative handoff.
955- Hydration applies rows as committed synced state without invoking mutation
956 handlers or creating optimistic state.
957- Hydration and adapter sync begin in a deterministic order: pending rows and
958 sync metadata are imported before sync starts.
959- `DbClient` owns collection instances and ambient transaction scope; cleanup
960 releases both.
961- Incremental chunks use the same collection payload shape as full dehydration.
962- Streamed live-query promises resolve to live-query result snapshots.
963
964### Deprecated
965
966- React dependency arrays for `useLiveQuery` and wrappers that delegate to it.
967 They still work and warn in development. They are planned for removal in 1.0.
968
969### Not Changed
970
971- `createCollection(...)` remains available.
972- Direct collection runtime APIs remain available.
973- Vue, Solid, and Angular keep their existing dependency/reactivity model until
974 they get their own SSR/client-provider work. Svelte is covered by this change.
975- Query collection `queryKey` is still TanStack Query's cache key. It is
976 separate from React live query identity.
977
978## Validation
979
980The SSR strategy is covered by:
981
982- core `DbClient` tests for hydration, streaming chunks, sync metadata,
983 initial data precedence, explicit ids, and no optimistic serialization
984- React tests for `DbProvider`, descriptor resolution, derived query identity,
985 `queryKey`, deprecation warnings, SSR result snapshots, and atomic handoff
986- Svelte tests for provider ownership, server snapshot rendering, and browser
987 handoff
988- query adapter tests to ensure Query cache behavior still holds
989- persistence core tests to ensure persisted row behavior remains intact
990- TanStack Start and Next.js Playwright E2Es that verify a Suspense fallback,
991 streamed query result, omitted source-only data, clean hydration, and atomic
992 replacement by browser sync