Skip to content

SSR

Server-side rendering in @nano_kit/query is built around two pieces: task tracking and cache dehydration.

Queries started during server render should be awaited before HTML is returned, and the resulting cache state should be transferred to the client for hydration. Task tracking is built in: every query attaches its request as a task to its data signal, so there is nothing to set up for it. Cache dehydration is the hydratable() setting.

Use hydratable() when query cache should be dehydrated on the server and rehydrated on the client. It is the whole SSR setting of a query client.

Without arguments, it reads hydration dependencies from the current injection context. Outside DI, pass them explicitly.

If the client uses codec(...), hydratable() encodes cached data before dehydration and decodes it during hydration.

import { client, dedupeTime, hydratable } from '@nano_kit/query'
const DEDUPE_TIME = 300_000 // 5 minutes
export function Client$() {
return client(
dedupeTime(DEDUPE_TIME),
hydratable()
)
}

This enables the usual SSR flow:

  1. Queries started during server render attach their requests as tasks to their data signals.
  2. The renderer waits for the tasks of the signals the page returns from Stores$, and of everything they depend on.
  3. Query cache state is dehydrated into the hydration payload.
  4. The client rehydrates the cache and reuses the prefetched data.

Two kinds of entries reach the client differently:

  • A request the server had not finished when it dehydrated the cache, such as one of a query read during render whose signal the page stores do not return, is made again in the browser rather than left loading.
  • An error the server rendered stays for the dedupe time, as an answer does, so the page does not ask for it again while it hydrates. An error that happens in the browser is asked again once its key is read again, see dedupeTime.