Server data, domain state
Where the server HTML matters (SEO: public lists and details), read server data with .suspend(arg)
in the Client Component that renders it:
'use client'
export function ProductDetail({ id }: { id: string }) {
const product = useProduct((s) => s.detail.suspend(id))
return <h1>{product.data?.title}</h1>
}
During SSR the server runs queryFn, renders the result, and streams it into the browser cache, so
hydration shows the same data without a second request. There is no Server Component fetch, no
initialProduct prop, and no route adapter: the folder structure is the same as for client-only
data. It needs two things: useServerInsertedHTML on the provider and a <Suspense> boundary.
Provider setup
Pass useServerInsertedHTML from next/navigation to ComwitProvider:
// app/providers.tsx
'use client'
import { ComwitProvider } from '@comwit/state'
import { useServerInsertedHTML } from 'next/navigation'
import type { ReactNode } from 'react'
export function Providers({ children }: { children: ReactNode }) {
return <ComwitProvider useServerInsertedHTML={useServerInsertedHTML}>{children}</ComwitProvider>
}
1. Define the query
queryFn runs on the server during SSR and in the browser afterwards, so call an API with an
absolute URL.
// state/product/index.ts
import { create, model, query } from '@comwit/state'
export type Product = { id: string; title: string; description: string }
const API_URL = process.env.NEXT_PUBLIC_API_URL
const product = model({
detail: query<Product | null, string>({
initialData: null,
staleTime: 30_000,
queryFn: async (id) => {
const response = await fetch(`${API_URL}/products/${encodeURIComponent(id)}`)
if (response.status === 404) return null
if (!response.ok) throw new Error('Could not load product')
return (await response.json()) as Product
},
}),
})
export const useProduct = create(product, { actions: [] })
2. Read it with .suspend()
The page only places the boundary. The component that reads the data owns the request.
// app/products/[id]/page.tsx
import { Suspense } from 'react'
import { ProductDetail } from './product-detail'
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Suspense fallback={<ProductSkeleton />}>
<ProductDetail id={id} />
</Suspense>
)
}
// app/products/[id]/product-detail.tsx
'use client'
import { useProduct } from '@/state/product'
export function ProductDetail({ id }: { id: string }) {
const product = useProduct((s) => s.detail.suspend(id))
if (!product.data) return <NotFound />
return (
<article>
<h1>{product.data.title}</h1>
<p>{product.data.description}</p>
</article>
)
}
server render: suspend(id) → queryFn → boundary HTML
↘ <script type="application/json" data-comwit-suspend> before that chunk
browser: hydrate boundary → suspend(id) reads the script → same snapshot, no queryFn → entry active after commit
Several components can suspend in one page (here with list and categories queries on their models); each boundary streams when its own queries resolve.
// app/products/page.tsx
<Suspense fallback={<CategoriesSkeleton />}>
<Categories />
</Suspense>
<Suspense fallback={<ProductGridSkeleton />}>
<ProductGrid page={page} />
</Suspense>
'use client'
function ProductGrid({ page }: { page: number }) {
const list = useProduct((s) => s.list.suspend({ page }))
return (
<section aria-busy={list.isFetching}>
{list.data.items.map((item) => (
<ProductCard key={item.id} product={item} />
))}
</section>
)
}
Changing the argument suspends again for the new key. Later refetches keep the current data visible;
use isFetching for a refresh indicator. Add an error boundary for failed requests.
Rules:
queryFnruns inside the Client Component bundle during SSR. Call a Route Handler or an external API; do not import database code or call Server Functions there.- On the server,
fetchneeds an absolute URL. - Results are transferred as JSON. Dates arrive as strings; convert them where the data is read.
- Keep the
<Suspense>boundary inside the provider. - The streamed entry keeps the server's fetch time, so
staleTimeapplies to later.load()and.query()calls. - Realtime queries, streaming
AsyncIterablefetchers,renderToString, and the Pages Router are not covered.
Without useServerInsertedHTML, server and browser caches stay separate and the browser runs
queryFn again while hydrating.
3. Client-only loading with .load()
Screens that do not need SEO (pages behind login, client-driven reads such as a quote that changes
with input) may use .load(arg) instead (here a reviews query). It does not request during SSR;
it renders isLoading first and starts after commit.
'use client'
function ProductReviews({ id }: { id: string }) {
const reviews = useProduct((s) => s.reviews.load(id))
if (reviews.isLoading) return <ReviewsSkeleton />
if (reviews.isError) return <ErrorMessage message={reviews.error} />
return <ReviewList reviews={reviews.data} />
}
Detail pages opened from a list
Give the detail query a seed and the
detail route paints the list item at once. The same .suspend(id) suspends and streams a direct
visit, and paints the seed before upgrading in the background when the list is already in the
model.
// state/product/index.ts
export type ProductSummary = Pick<Product, 'id' | 'title'>
const product = model({
list: query<ProductSummary[]>({ initialData: [], queryFn: () => api.product.list() }),
detail: query<Product | null, string, ProductSummary>({
initialData: null,
queryFn: (id) => api.product.find(id),
// paint the list item at once; the full detail replaces it in the background
seed: (id, { state }) => state.list.data.find((item) => item.id === id),
}),
})
// app/products/[id]/product-detail.tsx
'use client'
export function ProductDetail({ id }: { id: string }) {
const product = useProduct((s) => s.detail.suspend(id))
if (!product.data) return <NotFound />
return (
<article aria-busy={product.isPartial}>
<h1>{product.data.title}</h1>
{product.isPartial ? <DescriptionSkeleton /> : <p>{product.data.description}</p>}
</article>
)
}
app/products/[id]/page.tsx stays the static <Suspense> route above. The component renders the
summary fields while isPartial is true and the detail-only fields once the upgrade settles.
A seed works with both .load() and .suspend(). While a seed exists, .suspend(id) behaves like
.load(id) and does not throw a promise: it paints the seed and fetches the full detail after commit.
Choose who owns the request
| Data owner | Pattern |
|---|---|
| A public screen where server HTML matters (SEO) | .suspend(arg) with useServerInsertedHTML |
| A screen behind login or a client-driven read | .load(arg) and render loading/error state |
A framework without useServerInsertedHTML | Fetch on the server, then useDomain.hydrate(...) |
| A user event or coordinated workflow | An action calling .query(arg) or .refetch() |
| An IndexedDB-only fallback | Standalone local() with .restore(arg) |
Alternative: hydrate()
In a framework whose provider has no useServerInsertedHTML (or an equivalent) to pass, a server
response cannot reach the client cache, so navigating on the client requests it again. There, fetch
on the server and pass the result to hydrate(). Next.js does not need this; pass
useServerInsertedHTML instead. Local resources (local.query(), local.infinite()) are the
exception: they have no .suspend(), so their server data reaches the client through hydrate()
in Next.js too.
The shape of that call:
// app/products/[id]/page.tsx (Server Component)
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const initialProduct = await getProduct(id)
return <ProductRoute id={id} initialProduct={initialProduct} />
}
// app/products/[id]/product-route.tsx
;('use client')
export function ProductRoute({
id,
initialProduct,
}: {
id: string
initialProduct: Product | null
}) {
useProduct.hydrate({ detail: { arg: id, data: initialProduct } })
return <ProductDetail />
}
function ProductDetail() {
const product = useProduct((s) => s.detail.data)
return product ? <h1>{product.title}</h1> : <NotFound />
}
Call hydrate() unconditionally before the normal read of that model. It returns void, accepts
null / undefined, infers field names, arguments, and data, and never calls queryFn. Repeated
equivalent entries are no-ops; changes to an observed entry apply when the requesting render commits.
Supported fields: query(), query.infinite(), local.query(), and local.infinite().
Do not initialize state by calling an action in a render body.
URL search params during SSR
searchParam() fields read the request URL on the server when the
provider also receives getServerSearchParams:
<ComwitProvider
getServerSearchParams={getServerSearchParams}
useServerInsertedHTML={useServerInsertedHTML}
>
{children}
</ComwitProvider>
// app/get-server-search-params.ts
import { workUnitAsyncStorage } from 'next/dist/server/app-render/work-unit-async-storage.external.js'
/** Request search for searchParam() fields. Prerendering has no request, so the browser initializes. */
export function getServerSearchParams(): string | null {
if (typeof window !== 'undefined') return null
const store = workUnitAsyncStorage.getStore()
return store?.type === 'request' ? store.url.search : null
}
The request store is an internal Next.js module, so pin it per Next.js version and keep the getter in one file. The browser never calls it; hydration reads the transferred value.