Render a server-sent document
A server describes a page as data, and the client draws it with components. The server can ship a new layout without a client release, and the client does not trust what arrives: safeParseNode checks every node against its registration. This example is the full round trip. A route handler answers with a JSON document, a React component fetches it and draws each node with the component its $type names, and a node that fails validation is drawn as its issues in its own place, so the rest of the page still renders. The server in this example is newer than the client on purpose, so you see what the client does with a component it has never heard of.
Install
pnpm add @schema-engine/registry react react-dom zodThe server
orderDocument builds the document from an order, and GET is the route handler of /orders/:number. Any runtime that speaks Request and Response runs it: a Cloudflare Worker, Deno, Bun, Node with a router, or a Next.js route. It answers 404 for an order it does not know.
This server sends a badge with a warning tone and a countdown component. The client below knows neither.
export interface Order {
number: number;
paid: boolean;
trackingUrl?: string;
}
/**
* The document of an order page, as the server builds it.
*
* @remarks
* This server is newer than the client in the example: it sends a `warning` tone and a `countdown` component the
* client has not registered yet.
*/
export function orderDocument(order: Order): unknown[] {
return [
{
$type: 'callout',
tone: 'success',
title: `Order ${order.number} confirmed`,
text: 'Thanks for shopping with us.',
},
{ $type: 'badge', label: order.paid ? 'Paid' : 'Payment due', tone: order.paid ? 'success' : 'warning' },
{ $type: 'countdown', until: '2026-12-24T00:00:00Z' },
...(order.trackingUrl === undefined
? []
: [{ $type: 'button', label: 'Track parcel', href: order.trackingUrl }]),
];
}
const orders = new Map<number, Order>([
[1042, { number: 1042, paid: false, trackingUrl: '/parcels/1042' }],
[1043, { number: 1043, paid: true }],
]);
/** The route handler of `/orders/:number`: it answers with the order's document as JSON, or 404. */
export function GET(request: Request): Response {
const order = orders.get(Number(new URL(request.url).pathname.split('/').at(-1)));
return order ? Response.json(orderDocument(order)) : new Response('Not found', { status: 404 });
}The components
The client's design system is a registry of components. Each registration has a $type, the schema of its configuration and a render that draws it. The schema is the contract with the server: a tone or a link the schema does not allow never reaches render.
import type { ReactNode } from 'react';
import * as z from 'zod/mini';
import { createRegistry, type ComponentRegistration } from '@schema-engine/registry';
z.config(z.locales.en());
/** A registration of the design system: a `ComponentRegistration` whose `render` draws the component in React. */
export interface Component extends ComponentRegistration {
render(config: unknown): ReactNode;
}
/** A link target the design system accepts: a path on this site or an http(s) URL, never `javascript:`. */
const hrefSchema = z.string().check(z.regex(/^(\/|https?:\/\/)/, 'Use a path or an http(s) URL'));
const buttonSchema = z.object({
$type: z.literal('button'),
label: z.string(),
href: z.optional(hrefSchema),
variant: z.optional(z.enum(['primary', 'secondary'])),
});
const button: Component = {
$type: 'button',
schema: buttonSchema,
metadata: { name: 'Button', description: 'An action. With an href it is a link.', tags: ['action'] },
render({ label, href, variant = 'primary' }: z.output<typeof buttonSchema>) {
const className = `button button-${variant}`;
return href === undefined ? (
<button type="button" className={className}>
{label}
</button>
) : (
<a className={className} href={href}>
{label}
</a>
);
},
};
const badgeSchema = z.object({
$type: z.literal('badge'),
label: z.string(),
tone: z.optional(z.enum(['info', 'success', 'danger'])),
});
const badge: Component = {
$type: 'badge',
schema: badgeSchema,
metadata: { name: 'Badge', description: 'A short status label.', tags: ['status'] },
render({ label, tone = 'info' }: z.output<typeof badgeSchema>) {
return <span className={`badge badge-${tone}`}>{label}</span>;
},
};
const calloutSchema = z.object({
$type: z.literal('callout'),
title: z.string(),
text: z.optional(z.string()),
tone: z.optional(z.enum(['info', 'success', 'danger'])),
});
const callout: Component = {
$type: 'callout',
schema: calloutSchema,
metadata: { name: 'Callout', description: 'A message that stands out from the page.', tags: ['status'] },
render({ title, text, tone = 'info' }: z.output<typeof calloutSchema>) {
return (
<aside className={`callout callout-${tone}`}>
<strong>{title}</strong> {text && <span>{text}</span>}
</aside>
);
},
};
/** The components this client knows. A `$type` outside this registry is an issue, not an error. */
export const components = createRegistry('Component', [button, badge, callout]);The document component
DocumentView draws a list of nodes. For each node, safeParseNode looks the $type up in the registry and validates the node against the registration's schema, and it never throws. The third argument is where the node sits in the document, so every issue's path starts with the node's index. A node that passes is drawn by its registration. A node that fails is drawn as its issues, in its place.
ServerDocument fetches the document and hands it to DocumentView. A status that is not a success, a network failure and a body that is not JSON are one message, and the request is aborted when the component unmounts or the url changes.
import { Fragment, useEffect, useState } from 'react';
import { formatIssuePath, safeParseNode, type StandardSchemaIssue } from '@schema-engine/registry';
import { components } from './components.react';
function Fallback({ issues }: { issues: StandardSchemaIssue[] }) {
return (
<ul role="alert">
{issues.map(({ path, message }, index) => {
const where = formatIssuePath(path);
return <li key={index}>{where ? `${where}: ${message}` : message}</li>;
})}
</ul>
);
}
/**
* Draws each node of a document with the component its `$type` names.
*
* @remarks
* A node that fails validation is drawn as its issues, in its place, and the other nodes still render. Each issue's
* path starts with the index of the node.
*/
export function DocumentView({ nodes }: { nodes: unknown }) {
if (!Array.isArray(nodes)) return <Fallback issues={[{ message: 'A document is a list of nodes.', path: [] }]} />;
return (
<>
{nodes.map((node: unknown, index) => {
const parsed = safeParseNode(components, node, [index]);
return parsed.success ? (
<Fragment key={index}>{parsed.registration.render(parsed.data)}</Fragment>
) : (
<Fallback key={index} issues={parsed.issues} />
);
})}
</>
);
}
/** What the fetch of `url` ended with. Without a result for the current `url`, the document is still loading. */
type Loaded = { url: string } & ({ status: 'failed' } | { status: 'ready'; nodes: unknown });
/**
* Fetches the document at `url` and draws it.
*
* @remarks
* A status that is not a success, a network failure and a body that is not JSON are one message.
*/
export function ServerDocument({ url }: { url: string }) {
const [loaded, setLoaded] = useState<Loaded>();
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const headers = { Accept: 'application/json' };
const response = await fetch(url, { headers, signal: controller.signal });
setLoaded(
response.ok ? { url, status: 'ready', nodes: await response.json() } : { url, status: 'failed' },
);
} catch {
if (!controller.signal.aborted) setLoaded({ url, status: 'failed' });
}
}
void load();
return () => controller.abort();
}, [url]);
if (loaded?.url !== url) return <p>Loading the page</p>;
if (loaded.status === 'failed') return <p role="alert">The page could not be loaded.</p>;
return <DocumentView nodes={loaded.nodes} />;
}Run it
main.react.tsx draws the page into #root and exports the root, so the page can be unmounted. It calls routeFetchToLocalServer() from local-network.helper.ts, a file this page does not show, which answers every fetch with GET of server.ts, so the example runs without a network. Leave the call out to use a real server.
import { createRoot } from 'react-dom/client';
import { routeFetchToLocalServer } from './local-network.helper';
import { ServerDocument } from './server-document.react';
routeFetchToLocalServer();
export const root = createRoot(document.getElementById('root')!);
root.render(<ServerDocument url="https://shop.example/orders/1042" />);The callout and the button are drawn, and each node the client rejects is drawn as its issues:
<aside class="callout callout-success">
<strong>Order 1042 confirmed</strong>
<span>Thanks for shopping with us.</span>
</aside>
<ul role="alert">
<li>
[1].tone: Invalid option: expected one of
"info"|"success"|"danger"
</li>
</ul>
<ul role="alert">
<li>[2].$type: No registration for $type 'countdown'.</li>
</ul>
<a class="button button-primary" href="/parcels/1042">Track parcel</a>- The callout and the button are drawn. They are in the registry and their configuration is valid.
[1].toneis a configuration the client rejects. The badge is known, but its schema allowsinfo,successanddanger, so the server'swarningis reported at the field. The badge is not drawn, because a half-valid node is not shown.[2].$typeis a component the client has not registered. The path names the node by its index, so a log or an error report says exactly which part of the document the client could not draw.
The tests run the same files: the document of each order drawn to markup, the issues of a bad node, then the component in a browser against the route handler, with a 404, a network failure and a body that is not JSON.
Take it further
- Draw something better than a list in the fallback: the
pathand themessageof each issue are data, so the fallback can name the component or offer a retry. - Validate what a document may contain on the server too: build it from the same registry, so a document the client would reject never leaves the server.
- Draw a tree, not a list: Resolve a document passes each child its own
path. - Send workflows the same way, checked with
parseActions: Serialized workflows.