Skip to content

SSR

Server-side rendering (SSR) with stores requires isolating state per request and dehydrating data for client hydration. The Dependency Injection system ensures that each request gets its own signal instances, preventing state leakage between users.

Use hydratable to mark signals that should participate in dehydration/hydration. This assigns a unique key to each signal for later identification.

import { signal, hydratable, mountable } from '@nano_kit/store'
function User$() {
const $userId = hydratable('userId', signal(null))
const $user = hydratable('user', signal(null))
return { $userId, $user }
}

On the server, hydratable registers the signal in an internal map with its key. On the client, if dehydrated data exists for that key, the signal is immediately initialized with the hydrated value instead of the default.

hydratable also accepts a Codec as the third argument. You only need it when the dehydrated payload must serialize values that need custom encoding, such as Date, Map, Set, class instances, or encrypted/compact payloads.

import type { Codec } from '@nano_kit/store'
import { parse, stringify } from 'devalue'
import { signal, hydratable } from '@nano_kit/store'
interface DashboardSnapshot {
generatedAt: Date
selectedUserIds: Set<number>
usersById: Map<number, { name: string }>
}
const DevalueCodec: Codec<unknown, string> = {
encode: stringify,
decode: value => value === null ? null : parse(value)
}
function Dashboard$() {
const $snapshot = hydratable(
'dashboard',
signal<DashboardSnapshot | null>(null),
DevalueCodec
)
return { $snapshot }
}

On the server, the codec encodes the signal value before it is added to the dehydrated data. On the client, it decodes the dehydrated value before writing it into the signal.

Use isHydrated to check whether a signal has been populated from hydration data. The hydrated flag is cleared on the signal’s first user-driven update.

import { isHydrated, onMountEffect } from '@nano_kit/store'
function User$() {
/* ... */
onMountEffect($user, () => {
/* Subscribe to userId changes */
const userId = $userId()
/* Only fetch user data if it hasn't been hydrated from the server */
if (!isHydrated($user)) {
fetchUser(userId)
}
})
/* ... */
}

SSR requires waiting for all async operations to complete before dehydrating. Use task to attach an async operation to the signal it fills: until the operation settles, waitTasks of that signal, and of every signal that depends on it, waits for it.

import { signal, hydratable, mountable, onMountEffect, action, task } from '@nano_kit/store'
function User$() {
const $userId = hydratable('userId', signal(null))
const $user = hydratable('user', mountable(signal(null)))
const fetchUser = action((id) => task($user, async () => {
if (typeof id !== 'number') {
$user(null)
return
}
const response = await fetch(`/user/${id}`)
const user = await response.json()
$user(user)
}))
onMountEffect($user, () => {
fetchUser($userId())
})
return { $userId, $user }
}

task takes the signal the operation fills (or an array of signals) and a promise or a function that returns one, and returns that promise. waitTasks($signal) walks the dependency graph of the signal and waits, wave by wave, until neither the signal nor anything it depends on has tasks left, so a task started by another task and a dependency read only after a value settles are awaited too.

pendingTasks($signal) makes the same walk at once and tells whether there is anything to wait for. It returns a promise that settles as waitTasks does, or undefined when no task is pending. Use it where the answer is needed synchronously. For example, a render can write a value right away when its data is already in, and wait only when it is not.

There is no pool to create or provide: tasks live on the signals they fill, so dehydrate waits for exactly the stores it starts, and a test waits for exactly the signal it checks. Queries of @nano_kit/query and resolved attach their tasks by themselves, so stores built on them need no task call.

On the server, use dehydrate to execute your store logic, wait for its async tasks to complete, and extract the dehydrated key-value pairs.

import { dehydrate, inject } from '@nano_kit/store'
/* Server-side handler */
const dehydrated = await dehydrate(() => {
const { $userId, $user } = inject(User$)
/* Set initial data */
$userId(1)
/* Return signals to trigger mount and start async operations */
return [$user]
})
/* dehydrated = [['userId', 1], ['user', { name: 'John', email: '...' }]] */

The dehydrate function:

  1. Creates an injection context, or uses the context passed as the second argument
  2. Runs your store factories within that context
  3. Starts effects to trigger onMount callbacks (which start async tasks)
  4. Waits for the tasks of the returned signals and of every signal they depend on
  5. Collects all signals marked with hydratable
  6. Returns the dehydrated key-value pairs

If your stores need preconfigured dependencies, pass them as the second argument. It can be an InjectionContext instance or an array of providers for a new context.

import { dehydrate, provide } from '@nano_kit/store'
const dehydrated = await dehydrate(Stores$, [
provide(UserId$, 1)
])

On the client, pass the dehydrated data to a StaticHydrator and provide it via the Hydrator$ injection token.

import { Hydrator$, StaticHydrator, provide } from '@nano_kit/store'
import { InjectionContextProvider, useInject, useSignal } from '@nano_kit/react'
/* Dehydrated data passed from the server (e.g. via a script tag or window variable) */
const hydrator = new StaticHydrator(window.__DEHYDRATED__)
/* Component that provides the injection context with hydration data */
function App() {
return (
<InjectionContextProvider context={[provide(Hydrator$, hydrator)]}>
<UserProfile />
</InjectionContextProvider>
)
}
/* Component that uses the User$ store with hydrated data */
function UserProfile() {
const { $user } = useInject(User$)
const user = useSignal($user)
/* ... */
}

StaticHydrator is a one-shot hydrator: it applies values from the initial dehydrated snapshot and discards them after use. For streaming SSR where chunks of dehydrated data arrive after the initial render, use ActiveHydrator instead — it exposes a push(dehydrated) method to feed additional data reactively.

In the development build, StaticHydrator warns about an id that has no value in the snapshot: the signal was not dehydrated on the server, or the same id is hydrated twice.