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. The adapter's first insert for the same key
649replaces the provisional row and its row metadata instead of raising a
650duplicate-key error; an insert without metadata clears the seed's metadata.
651An adapter update merges over the provisional row like any update. A hydrated
652row that arrives after the adapter has written its key, or while the adapter's
653transaction for it is open, does not change what the adapter wrote: it only
654supplies a row or row metadata that the adapter has not written. Row data and
655row metadata count separately, so a later hydrated row can still supply
656metadata for a key whose row the adapter only updated. After an adapter delete
657or truncate, a later hydrated row does not bring the key back. Among hydrated
658rows for a key the adapter has not written, the latest one wins, including its
659row metadata or the lack of it.
660
661Hydrated rows and `initialData` never mark adapter sync as ready by themselves.
662The adapter still owns readiness through its sync lifecycle.
663
664## React Query Identity
665
666React hooks derive live query identity from structured query IR by default:
667
668```tsx
669function Todos({ status }: { status: string }) {
670 return useLiveQuery({
671 query: (q) =>
672 q
673 .from({ todo: todoCollection })
674 .where(({ todo }) => eq(todo.status, status)),
675 })
676}
677```
678
679The captured `status` value is represented in the structured IR, so no
680dependency array or `queryKey` is required.
681
682Use `queryKey` when the query contains opaque runtime logic that DB cannot
683stably represent:
684
685```tsx
686function SearchTodos({ search }: { search: string }) {
687 return useLiveQuery({
688 queryKey: [todoCollection.id, 'search', search],
689 query: (q) =>
690 q
691 .from({ todo: todoCollection })
692 .fn.where(({ todo }) =>
693 todo.title.toLowerCase().includes(search.toLowerCase())
694 ),
695 })
696}
697```
698
699Common reasons to add `queryKey`:
700
701- `.fn.where(...)`
702- `.fn.select(...)`
703- `.fn.having(...)`
704- function values, symbols, class instances, or circular objects captured inside
705 the structured query
706- a render path where derived identity becomes measurably expensive
707
708When structured IR cannot be hashed and the query has no `queryKey`, a hook
709that compares identity throws `UnhashableQueryIRError`: React and Preact hooks,
710and any hook backed by a `DbClient`, which matches queries by identity hash. An
711empty `queryKey` counts as none. Represent the values that opaque logic
712captures in `queryKey`, so the query recompiles when they change.
713
714DB also warns once in development if deriving identity becomes expensive enough
715that an explicit `queryKey` would be better.
716
717Dependency arrays are accepted for backwards compatibility:
718
719```tsx
720useLiveQuery((q) => q.from({ todo: todoCollection }), [status])
721```
722
723They warn in development and will be removed in 1.0. Migrate to the config
724object form:
725
726```tsx
727useLiveQuery({
728 query: (q) => q.from({ todo: todoCollection }),
729})
730```
731
732Add `queryKey` only if the query uses opaque logic or trips the performance
733warning.
734
735## Migration Guide
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>
782)
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)
796}
797
798function TodoActions({ id }: { id: string }) {
799 const todos = useTodoCollection()
800
801 return (
802 <button onClick={() => todos.delete(id)}>
803 Delete
804 </button>
805 )
806}
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 [status],
824)
825
826// After
827useLiveQuery({
828 query: (q) =>
829 q
830 .from({ todo: todoCollection })
831 .where(({ todo }) => eq(todo.status, status)),
832})
833```
834
835If the query uses opaque functional variants, add `queryKey`:
836
837```tsx
838useLiveQuery({
839 queryKey: [todoCollection.id, 'status-fn', status],
840 query: (q) =>
841 q
842 .from({ todo: todoCollection })
843 .fn.where(({ todo }) => todo.status === status),
844})
845```
846
847### 6. Preload and dehydrate on the server
848
849Preload a collection when the browser should receive normalized source rows:
850
851```tsx
852const dbClient = new DbClient()
853const todos = dbClient.collection(todoCollection)
854await todos.preload()
855
856return {
857 dbState: dbClient.dehydrate(),
858}
859```
860
861Preload a live query when the browser only needs the rendered result:
862
863```tsx
864const dbClient = new DbClient()
865await dbClient.preloadLiveQuery({ query: openTodosQuery })
866
867return {
868 dbState: dbClient.dehydrate(),
869}
870```
871
872### 7. Hydrate before client hooks read DB
873
874```tsx
875<DbProvider client={client}>
876 <HydrationBoundary state={loaderData.dbState}>
877 <App />
878 </HydrationBoundary>
879</DbProvider>
880```
881
882Imperative integrations can call `client.hydrate(loaderData.dbState)` before
883rendering instead.
884
885## Compatibility
886
887No existing public API is removed by this change.
888
889Still supported:
890
891- `createCollection(...)`
892- passing collection instances to `useLiveQuery(...)`
893- `useLiveQuery(queryFn, deps)`
894- `useLiveSuspenseQuery(queryFn, deps)`
895- mutation APIs such as `insert`, `update`, `delete`, `subscribe`, and
896 optimistic mutation helpers
897
898Warnings:
899
900- React dependency arrays warn in development and will be removed in 1.0.
901- Opaque query IR without `queryKey` throws `UnhashableQueryIRError` in a
902 hook that compares identity (React, Preact, or any `DbClient`-backed hook).
903- Expensive derived identity warns in development and suggests `queryKey`.
904
905Required for SSR:
906
907- stable explicit collection ids
908- request-scoped server `DbClient`
909- browser-scoped client `DbClient`
910- `DbProvider` for descriptor resolution in React
911- `dehydrate()` on the server and `hydrate()` in the browser
912
913Required for render-time Suspense streaming:
914
915- `routerWithDbClient(router, dbClient)`
916- `useLiveSuspenseQuery(...)` inside a Suspense boundary
917- a stable derived query identity or explicit serializable `queryKey`
918
919## Detailed Changelog
920
921### Added
922
923- `DbClient`
924- `collectionOptions(...)`
925- `CollectionOptions` descriptor type
926- `CollectionMaterializeOptions`
927- `DehydratedDbState`
928- `DehydratedCollectionChunk`
929- `DehydratedCollectionRow`
930- `dbClient.collection(descriptor, options?)`
931- `dbClient.dehydrate()`
932- `dbClient.hydrate(state)`
933- `dbClient.applyCollectionChunk(chunk)`
934- `dbClient.subscribe(listener)`
935- `dbClient.createTransaction(config)`
936- `dbClient.cleanup()`
937- React `DbProvider`
938- React `useDbClient()`
939- React `useOptionalDbClient()`
940- React `HydrationBoundary`
941- React descriptor resolution inside live query builders
942- React derived structured query identity
943- React `queryKey` escape hatch for opaque or hot-path queries
944- React per-query `client` override
945- SSR-capable `useSyncExternalStore` server snapshot support
946- `dbClient.preloadLiveQuery(...)`
947- Svelte `DbProvider`, `useDbClient()`, descriptor resolution, and synchronous
948 server snapshot support
949- TanStack Start and Next.js Playwright SSR E2E coverage
950- `@tanstack/react-router-with-db`
951- render-time `useLiveSuspenseQuery` promise streaming
952
953### Changed
954
955- React `useLiveQuery({ query })` can use collection descriptors directly in
956 `from`, `join`, `leftJoin`, and `unionAll` sources when a `DbProvider` is
957 present.
958- React live query identity is derived from normalized structured IR when no
959 explicit `queryKey` or legacy dependency array is supplied.
960- Explicit collection preloading serializes normalized collection rows.
961- Live-query preloading and render-time discovery serialize ordered result
962 snapshots without implicitly serializing source collections.
963- Browser observers keep the hydrated result visible while normal source sync
964 starts, then publish one authoritative handoff.
965- Hydration applies rows as committed synced state without invoking mutation
966 handlers or creating optimistic state.
967- Hydration and adapter sync begin in a deterministic order: pending rows and
968 sync metadata are imported before sync starts.
969- `DbClient` owns collection instances and ambient transaction scope; cleanup
970 releases both.
971- Incremental chunks use the same collection payload shape as full dehydration.
972- Streamed live-query promises resolve to live-query result snapshots.
973
974### Deprecated
975
976- React dependency arrays for `useLiveQuery` and wrappers that delegate to it.
977 They still work and warn in development. They are planned for removal in 1.0.
978
979### Not Changed
980
981- `createCollection(...)` remains available.
982- Direct collection runtime APIs remain available.
983- Vue, Solid, and Angular keep their existing dependency/reactivity model until
984 they get their own SSR/client-provider work. Svelte is covered by this change.
985- Query collection `queryKey` is still TanStack Query's cache key. It is
986 separate from React live query identity.
987
988## Validation
989
990The SSR strategy is covered by:
991
992- core `DbClient` tests for hydration, streaming chunks, sync metadata,
993 initial data precedence, explicit ids, and no optimistic serialization
994- React tests for `DbProvider`, descriptor resolution, derived query identity,
995 `queryKey`, deprecation warnings, SSR result snapshots, and atomic handoff
996- Svelte tests for provider ownership, server snapshot rendering, and browser
997 handoff
998- query adapter tests to ensure Query cache behavior still holds
999- persistence core tests to ensure persisted row behavior remains intact
1000- TanStack Start and Next.js Playwright E2Es that verify a Suspense fallback,
1001 streamed query result, omitted source-only data, clean hydration, and atomic
1002 replacement by browser sync