Server Rendering and Isolation
Server rendering can reuse Query’s cache during one request, but a server process usually serves many users. A request-scoped instance belongs to one incoming request and is never reused by another user’s rendering work. Create that instance inside your framework’s request handler or loader, not in a module-level singleton.
The browser may keep its own instance across navigation within one authenticated scope. It must not inherit another request’s server instance. This page describes the data boundary; your framework still owns routing, HTML rendering, request credentials, and transport of initial page data.
Create the server client inside the request
Section titled “Create the server client inside the request”The server has no browser base URL or implicit cookie jar. Use absolute URLs and explicitly forwarded request credentials where appropriate. Do not forward cookies to a URL chosen by untrusted input.
This complete factory restricts reads to one configured API origin. Call it once inside each request handler, using an application-controlled origin and that incoming request’s cookie header:
import { createQuery } from '@studiolambda/query'
/** Creates one authenticated data owner without retaining another request's state. */export function createRequestQuery(apiOrigin: string, cookie: string | null) { const origin = new URL(apiOrigin).origin return createQuery({ fetcher: async (key, { signal }) => { const url = new URL(key, origin) if (url.origin !== origin) throw new Error('untrusted API origin') const response = await fetch(url, { signal, redirect: 'error', headers: cookie === null ? {} : { Cookie: cookie }, }) if (!response.ok) throw new Error(`API request failed: ${response.status}`) return response.json() }, })}Redirects are rejected so credentials are not accidentally forwarded along an unreviewed redirect chain. Choose a stricter path allowlist if untrusted callers can supply keys. For a production backend, also apply your network/SSRF policy; a same-origin URL check is not a full network sandbox.
With createRequestQuery imported, a framework loader’s operation is conceptually:
const query = createRequestQuery('https://api.example.com', request.headers.get('cookie'))const profile = await query.query<Profile>('/api/profiles/1', { stale: false })This is a loader fragment, not a runnable server: request is your framework’s incoming Request, Profile is your validated application type, and api.example.com must be replaced with your controlled backend. Catch failures in the loader according to the framework’s error-response policy. Pass this same query to the rendered tree only for this request.
If the client disconnects and the framework provides a request-cancellation signal, your handler can call query.abort() on that isolated instance. Remove any signal listener during handler cleanup. Do not use blanket cancellation on a process-global client that other requests share.
Transfer values, not live stores
Section titled “Transfer values, not live stores”Query does not provide a dehydrate/serialize API. caches() contains promises, dates, and controllers and is not a transport format. Select only the browser-safe data your page needs, using awaited loader results or snapshot() for known keys, and send it through the framework’s safe page-data serialization.
Treat that output as public to the receiving browser. Exclude server credentials, internal-only fields, and data the current user must not inspect. If embedding JSON in HTML yourself, escape it correctly for the HTML context; JSON.stringify alone does not prevent a value containing </script> from breaking out of a script element. Prefer the framework’s established serializer instead of constructing script markup.
You must define validation, supported value types, and versioning for the handoff. A JSON round-trip does not preserve arbitrary class instances, functions, dates as dates, or object identity.
Seed the browser before rendering readers
Section titled “Seed the browser before rendering readers”In browser bootstrap, create the browser’s own stable instance and hydrate a validated initial value before mounting the application. The following function is framework-independent and assumes the framework has already delivered and validated a profile:
import { createQuery } from '@studiolambda/query'
/** Browser-safe initial profile representation. */interface Profile { readonly id: number readonly name: string readonly role: string}
/** Prepares a client before React hydration or another UI's first read. */export function createBrowserQuery(profile: Profile) { const query = createQuery() query.hydrate('/api/profiles/1', profile, { expiration: () => 30_000 }) return query}Pass the result to QueryProvider before hydrateRoot when using React. Server and browser readers must agree on key and representation. The 30-second lifetime begins when this browser seed is committed; it does not preserve the server’s original absolute expiration. If the data’s age matters, compute an appropriate remaining lifetime from trusted handoff metadata.
Omitting hydration expiration makes the data immediately stale. With default stale: true, the first read may already request a refresh while returning the seed. That is suitable when intentional, but not if you expected hydration alone to prevent duplicate loading.
Account for React render lifetimes
Section titled “Account for React render lifetimes”React Suspense can retry a render that never committed. Query’s fresh resources deliberately keep that selection available, including failed or abandoned initial reads, until invalidation or instance collection. A process-global instance can therefore retain more than ordinary committed cache data. Request isolation is required even if you plan to clear item entries later.
Browser prefetch and incoming broadcast subscriptions run in effects, not during server rendering. QueryPrefetchTags can output resource hints, but its Query reads still occur only in the client effect. Use explicit awaited server preparation for data the server render needs.
If a fresh initial read fails, resetting only the error boundary can reuse the rejected selection. Invalidate before retrying. Do not use repeated fresh imperative calls during render to work around Suspense; use the data hook’s resource lifecycle.
End an authenticated scope
Section titled “End an authenticated scope”On logout or tenant change, remove the old consumers, unsubscribe application listeners, cancel no-longer-needed reads on the old isolated instance, and close caller-owned channels only after every user has detached. Then create a new instance for the new scope.
Neither forget() nor provider unmount cancels queued mutation functions or rolls back server effects. Old operations can still settle for their original callers. Prevent those callers from publishing into the new UI through application-owned scope checks and by not reusing the old client.
Cross-tab communication is disabled unless you supply a channel. Channel labels reduce accidental cross-talk but are not authentication or tenant enforcement. Omit channels on the server and share only browser-safe event data among intended same-origin participants.