Relay
Server rendering
On this page
This site renders every page on the server with React Router and Relay, and the browser hydrates it without a single GraphQL request. The deferred related-pages panel and the streamed changelog are in the HTML too: the server waits for every payload of a route's query before it renders. On a later client navigation, the same query runs over /graphql: the current page stays on screen until the next page's initial payload is in, and its deferred and streamed parts render as they arrive. Going back to a page you have just seen, once its whole response is in, renders it from Relay's store, with no request.
The contract
- On a document request, the route's server loader runs its query in process, waits for every payload (
@deferand@streamincluded), converts them into Relay payloads, and returns them as one array. The HTML is complete, a CDN can cache it, and hydration makes no request. - In the browser, the route puts those payloads into its Relay environment's response cache and loads the query from there, so the server render and the hydration read the same data. Once the page has hydrated, the entry is removed, so a later navigation back never reads stale payloads.
- On a client navigation, the route's
clientLoadercallsloadQueryover/graphql, and never calls the server loader. It waits for the query's initial payload, so the current page stays on screen, under a slim progress bar, until the next one can render; the deferred and streamed parts arrive after it, each with its own small fallback. - On a back navigation, the
clientLoaderfinds the page's data in Relay's store (store-or-network) and makes no request: the page renders at once, whether it was hydrated or loaded on the client. That holds only for a page whose last load completed cleanly: every payload arrived, and none carried errors. A page left mid-stream, or one whose response carried errors, is fetched again (network-only). Relay's store keeps the ten queries released last.
A docs page's two loaders, the server's and the client's, answer a missing page the same way, with a 404:
const pageFound = <D extends QueryData<pageQuery>>(loaded: D): D => {
if (!found(loaded, "page")) {
if ("ref" in loaded) {
loaded.ref.dispose();
}
// A null page with errors is a failed lookup (the server's fault); without, an absent page.
// oxlint-disable-next-line typescript/only-throw-error -- a loader answers a status this way.
throw failed(loaded)
? data("The page could not be loaded.", { status: 500 })
: data("No such page.", { status: 404 });
}
return loaded;
};
export const loader = async ({ request, params, context }: LoaderFunctionArgs) =>
pageFound(await preload<pageQuery>(context, request, query, { slug: params["slug"] ?? "" }));
export const clientLoader = async ({ request, params }: ClientLoaderFunctionArgs) =>
pageFound(
await loadInitial<pageQuery>(
clientEnvironment(),
query,
{ slug: params["slug"] ?? "" },
request.signal,
),
);Waiting for the initial payload
loadInitial serves a query from the store only when its last load completed cleanly: every payload arrived (the response ended with hasNext: false), none carried errors, and no deferred fragment or stream failed. Relay cannot tell this itself: a load left mid-stream leaves partial data that Relay calls available, the deferred parts in and some streamed items not, and so does a stream that failed, which ends the response like any other and is in no payload: only the fetch function's onFailure sees it. A response with errors is complete data too. So the loader keeps the set of operations (each query with its variables) whose last load completed cleanly. A load from the network takes its operation out of the set, and puts it back once it completes with no errors and no failure; a hydrated query is in the set when its payloads carry no errors and its server loader saw no failure (hadFailures, beside the payloads). A query in the set is loaded with store-or-network: when the store still holds its data, loadQuery makes no request and its reference has no source, so the loader returns at once. Any other is loaded with network-only. Each load hands the fetch function a listener of its own, in networkCacheConfig's metadata, and the fetch function reports each failure of that load's response to it:
let clean = true;
const fetchPolicy = complete.has(id) ? "store-or-network" : "network-only";
const ref = loadQuery<T>(environment, query, variables, {
fetchPolicy,
// The fetch function reports a failed deferred fragment or stream of this load's response here.
networkCacheConfig: {
metadata: failureMetadata(() => {
clean = false;
}),
},
});Otherwise it subscribes to ref.source and resolves at its first next, once Relay has written the initial payload to the store. source replays the one request loadQuery started, so reading it starts no second one, and neither does usePreloadedQuery, which reads the same source and renders without suspending. The rest of the response keeps streaming into the store. A request that fails before its initial payload rejects, so React Router's error handling applies, and so does one that sends no payload within 30 seconds, and a navigation that is cancelled. Two navigations to a page whose query is still loading share its one request, which is cancelled once both have left.
A navigation is a transition, and in one React keeps the previous page on screen rather than hide a Suspense boundary that already shows content. So the related-pages panel's boundary, the docs route's one deferred panel, is keyed by its page: a new page mounts a new boundary, which shows its fallback while the panel streams in.
Preloading in process
The loader does not fetch /graphql over the network: it runs the GraphQL route in process, inside the document request's Effect context, which React Router's load context hands down. So the query shares the page's trace, and it is cancelled with the page:
const { params } = getRequest(query);
const graphql = context.get(graphqlContext);
const { payloads, hadFailures } = await graphql.execute(
new Request(new URL("/graphql", request.url), {
method: "POST",
headers: { "content-type": "application/json", accept: ACCEPT },
body: requestBody(params, variables),
// Aborted with the document request: the query is cancelled with the page.
signal: request.signal,
}),
async (response) => {
const all: Array<GraphQLSingularResponse> = [];
let failed = false;
await readResponse(
response,
(payload) => {
all.push(payload);
},
() => {
failed = true;
},
);
return { payloads: all, hadFailures: failed };
},
);
return { preloaded: { key: cacheKeyOf(params), variables, payloads, hadFailures } };
};The host builds a Request for the query, runs effectRoute(server) on it, and keeps the run's scope open until the response has been read to its end: closing it earlier would count as a cancel. The run is tied to the document request's abort signal:
export const inProcess = (server: Server, context: Context.Context<never>): InProcessGraphQL => {
const route = effectRoute(server);
return {
execute: (request, read) =>
Effect.runPromiseWith(context)(
Effect.scoped(
route(HttpServerRequest.fromWeb(request)).pipe(
Effect.flatMap((response) =>
Effect.promise(() => read(HttpServerResponse.toWeb(response, { context }))),
),
),
),
{ signal: request.signal },
),
};
};Hydrating from the payloads
The route component hydrates its query: hydrate puts the loader's payloads into the environment's response cache and loads the query from it. The server loader read every payload, so the query has completed cleanly when none of them carries errors and nothing of the response failed, and a later navigation back may then read it from the store:
export const hydrate = <T extends OperationType>(
environment: Environment,
query: GraphQLTaggedNode,
{ key, variables, payloads, hadFailures }: Preloaded<T>["preloaded"],
): PreloadedQuery<T> => {
const complete = completeIn(environment);
const id = identifierOf(query, variables);
if (hadFailures || payloads.some(hasErrors)) {
complete.delete(id);
} else {
complete.add(id);
}
cacheOf(environment).set(key, variables, [...payloads]);
return loadQuery<T>(environment, query, variables, { fetchPolicy: "network-only" });
};usePreloaded clears the cache once the page has hydrated. It takes over a query its clientLoader loaded (claim): until then, an aborted navigation releases the query, and so do 10 seconds without a claim, since React Router may replace a loader's result before its route commits, without aborting its signal. A route that renders after its query was released (behind a slow route chunk, say) loads it again, through the same tracked load, rather than reading it disposed.
/**
* The query a route renders: hydrated from its server loader's payloads, or the clientLoader's.
* A clientLoader's query released before its route rendered (it waited past UNCLAIMED_RELEASE_MS,
* say behind a slow route chunk) is loaded again, from the network, rather than read disposed.
*/
export const queryFor = <T extends OperationType>(
environment: Environment,
query: GraphQLTaggedNode,
data: QueryData<T>,
): PreloadedQuery<T> => {
if ("preloaded" in data) {
return hydrate<T>(environment, query, data.preloaded);
}
if (!data.ref.isDisposed) {
return data.ref;
}
// The same tracked load a clientLoader makes (start), so the reload counts toward the operation's
// clean completion like any other.
const { variables } = data.ref;
const id = identifierOf(query, variables);
const shared = inFlightIn(environment).get(id) ?? start<T>(environment, id, query, variables);
shared.owners += 1;
let released = false;
return {
...shared.ref,
variables,
dispose: () => {
if (!released) {
released = true;
shared.leave();
}
},
get isDisposed() {
return released;
},
};
};
/** The route's query: loaded from its server loader's payloads, or the clientLoader's. */
export const usePreloaded = <T extends OperationType>(
query: GraphQLTaggedNode,
data: QueryData<T>,
): PreloadedQuery<T> => {
const environment = useRelayEnvironment();
const ref = useMemo(() => queryFor(environment, query, data), [environment, query, data]);
useEffect(() => {
if ("preloaded" in data) {
// Hydrated: a later navigation back to this page never reads these payloads again.
cacheOf(environment).clear();
} else if (ref === data.ref) {
data.claim();
}
return () => {
ref.dispose();
};
}, [environment, data, ref]);
return ref;
};The environments differ on each side. On the server, each document request gets an environment of its own, whose fetch function answers only from the response cache: a query its loader did not preload is an error, never a request. In the browser there is one environment, over /graphql, which reads the cache first:
export const createServerEnvironment = (): Environment =>
make(true, (cache) => {
const fetchFn: FetchFunction = (params, variables) => {
const cached = cache.get(cacheKeyOf(params), variables);
return cached === null
? Observable.create((sink) => {
sink.error(new Error(`${params.name} was not preloaded by its route's loader.`));
})
: Observable.from(cached);
};
return Network.create(fetchFn);
});Rendering the whole tree
The document waits for every Suspense boundary (allReady) before it responds. React would still outline a large boundary: it would send the fallback in place, then the content later in the response, swapped in by a script. With no progressive chunk limit, every boundary is rendered in place:
const body = await renderToReadableStream(
<RelayEnvironmentProvider environment={createServerEnvironment()}>
<ServerRouter context={routerContext} url={request.url} />
</RelayEnvironmentProvider>,
{
signal: request.signal,
progressiveChunkSize: Number.POSITIVE_INFINITY,
onError(error: unknown) {
status = 500;
// oxlint-disable-next-line no-console -- the server's log is where a render error goes.
console.error(error);
},
},
);One copy of each module
The server build leaves gratos-server, effect and graphql external (Vite's ssr.external), so the host process and the build share one instance of each, and their module state (the server's per-request maps, the Effect layer's route state) is never split:
ssr: { external: ["gratos-server", "effect", "graphql"] },The site's tests check all of it: a document holds every deferred and streamed part, two concurrent renders each get only their own records, the in-process query has the document's trace id and is aborted with it, and a production start loads each of those packages once.