Custom Renderers
Farm.js renders pages through a renderer: a descriptor and three modules. React, Preact, Solid, Vue, and Svelte are written against the same contract, and so is any UI library you want to bring. This page covers the whole contract in the order you'd build one.
examples/custom-renderer
is a complete renderer to copy from. It renders an app with leaf, a small UI library Farm.js has no
code for, through an adapter written in plain JavaScript. Most snippets on this page come from it.
What the renderer owns
Farm.js keeps the parts of an app that don't depend on the UI library:
- Route discovery, layouts, loading, error, and not-found files, and route metadata
- API routes, server functions and queries, middleware, cache, and storage
- Client navigation, prefetching, the query cache, theme, and i18n state
- Production builds and every deployment target
The renderer does the rest:
- Compiling components, through a Vite plugin.
- Building and rendering element trees on the server, to a string or a stream.
- Hydrating that markup in the browser, and rendering the next route on a client navigation.
- Hooks or bindings that let components read Farm.js's client state.
A custom renderer gets the same Farm.js features as Solid, Vue, and Svelte. The feature table lists them. React Server Components are React-only; islands work with any renderer that declares them (see Islands).
How Farm.js uses a renderer
farm.config.tssetsrendererto a descriptor. The descriptor names modules by package specifier; it holds no functions, so the config stays serializable.farm devandfarm buildimport the Vite module and add its plugin to the browser graph and the server graph.- On a request, Farm.js imports the server module, builds the route tree with its
createElement()(layouts around the page, aSuspenseboundary where a loading file applies), and renders it: through a stream when the renderer declares one, otherwise withrenderToString(). - In the browser, Farm.js builds the same tree with the client module's
createElement()and hands it tohydrateRoot(), for pages and layouts that hydrate. - On a client navigation, Farm.js loads the next route's modules and builds its tree. When a hydrating
layout stays on screen, Farm.js hands the tree to the existing root's
render(), orrenderRoute()when the root has one. Otherwise it unmounts the old root and renders into a new one. - Components read the router, server queries, actions, theme, and i18n through stores from
@farm.js/core/renderer-client. The renderer turns those stores into hooks.
Package layout
A renderer is a package with one entry per module:
farm-leaf/
package.json
src/index.js the descriptor farm-leaf
src/server.js the server module farm-leaf/server
src/client.js the client module farm-leaf/client
src/vite.js the Vite module farm-leaf/vite
src/bindings.js hooks and a Link farm-leaf/bindings{
"name": "farm-leaf",
"type": "module",
"sideEffects": false,
"exports": {
".": { "types": "./src/index.d.ts", "default": "./src/index.js" },
"./server": { "types": "./src/server.d.ts", "default": "./src/server.js" },
"./client": { "types": "./src/client.d.ts", "default": "./src/client.js" },
"./vite": { "types": "./src/vite.d.ts", "default": "./src/vite.js" },
"./bindings": { "types": "./src/bindings.d.ts", "default": "./src/bindings.js" }
},
"peerDependencies": {
"@farm.js/core": "*",
"leaf": "*",
"vite": "*"
}
}- Make
@farm.js/coreand the UI library peer dependencies, so the adapter uses the app's copies. The router and the query cache are module state, so a second copy of core would hold a second router and cache. - Farm.js resolves each module from the app's
package.json, so the specifiers must resolve from the app, not only from inside the renderer package. - Import from
@farm.js/core/rendererand@farm.js/core/renderer-client, never from the@farm.js/coreroot. The root entry imports React, which an app on another renderer doesn't install.
The descriptor
The descriptor is what an app passes to renderer. Export a function that returns one, so each app
gets its own copy:
// src/index.js
import { defineRenderer } from "@farm.js/core/renderer";
export function leaf() {
return defineRenderer({
name: "leaf",
vite: "farm-leaf/vite",
server: "farm-leaf/server",
client: "farm-leaf/client",
jsxImportSource: "leaf",
componentExtensions: [".leaf"],
capabilities: {
streaming: { node: false, web: false },
reconcilesRerenders: true,
functionComponents: true,
hydrationFallback: true,
},
});
}// farm.config.ts in the app
import { defineConfig } from "@farm.js/core";
import { leaf } from "farm-leaf";
export default defineConfig({
renderer: leaf(),
});defineRenderer() returns its argument and types it as FarmRenderer. Farm.js checks the descriptor
when it resolves the config, and reports every bad field at once.
The module specifiers are what the app's server and browser code import. routes(), hydration,
and compile() are different: they're build-time hooks that run in Node while Farm.js scans the app,
and never reach the browser.
name(required): the renderer's id in errors and generated manifests.vite,server,client(required): the three module specifiers. Each must be a non-empty string, or the config fails withFarm renderer `server` must be a non-empty string.jsxImportSource: the package your JSX imports its runtime from. In development Farm.js passes it to Vite's dependency scan. Without it, the scan compiles JSX as React unless the app's tsconfig names a source, and an app with no React installed fails the scan and reloads on its first visit.componentExtensions: extensions of your own file format, such as[".leaf"]. Route files with them become pages and layouts, next to.ts,.tsx,.js, and.jsx. See Your own file format.routes(context): which files are routes and the URL each one serves, for a library with a convention other than Farm.js's folders. See Route files.hydration: which pages and layouts hydrate when they say nothing, and a reader for your format's own syntax for it. See Hydration.compile(source, file): the JavaScript or TSX module a file in your format compiles to, which Farm.js reads to plan what hydrates. See Your own file format.dedupe: packages that must resolve to one copy in the app, passed to Vite'sresolve.dedupe. List a runtime whose hooks keep module-level state.optimizeDeps: packages Vite pre-bundles in development before the first page load. Farm.js adds theclientmodule itself when it names a package, and@farm.js/core/renderer-client, which your bindings import.buildConcurrency:"parallel"(the default) or"serial". A production build compiles the browser and server graphs at the same time. Set"serial"when your compiler plugin keeps process-global mutable caches; the official Vue renderer does, because@vitejs/plugin-vueshares them between plugin instances.capabilities: what the renderer supports:streaming,reconcilesRerenders,functionComponents,hydrationFallback, andislands. Each defaults to off. Streaming is covered under Streaming; the next two under Components and Route updates;hydrationFallbackunder The client module;islandsunder Islands.options: serializable options your Vite module receives asrendererOptions. Use them for compiler modes, so the descriptor function can take options from the app.appSetup: a module path, relative to the project root, that configures each app instance your renderer creates (Vue'sapp.use(), for example). Farm.js imports it in the server and browser entries and passes its default export toconfigureApp(), which both runtime modules must then export.
The server module
Farm.js imports the server module by name in development and in the production server bundle. It needs no default export. Six exports are required:
// src/server.js
export { Fragment, Suspense, createElement, isValidElement } from "leaf";
export { renderToString } from "leaf/server";
export const name = "leaf";
export const capabilities = { streaming: { node: false, web: false } };name: a non-empty string, usually the descriptor'sname.createElement(type, props, ...children): Farm.js composes every route tree with it.typeis a tag name,Fragment,Suspense, or a component. Layouts get the page aschildren, and the route's params asparams.isValidElement(value): whether a value is one of your elements, as opposed to a string, a promise, or a plain object.FragmentandSuspense: the valuescreateElement()accepts as types. Farm.js wraps a page that has a loading file inSuspense, with the loading component asfallback.renderToString(element, options): renders a tree to HTML. It may return a promise. Farm.js uses it when the renderer doesn't stream, and for documents it sends whole: the not-found and error pages with their layouts.
farm dev and farm build check these exports when they load the module, and fail with one error
that names every missing export.
Farm.js's own components pass React-style props: className, htmlFor, event handlers such as
onClick, and numeric style values in pixels. Map them to what your library expects. Escape text
and attribute values in the HTML you write: Farm.js passes route params and query strings through as
props.
options.nonce is the CSP nonce of the response being rendered. Put it on every inline <script>
your renderer writes, such as hydration data or streaming reveals: under security.csp.nonce, the
browser blocks a script without it.
Optional server exports
renderToReadableStream()andrenderToPipeableStream(): streaming. See Streaming.renderToStringWithHead(element, options): for a library whose components write head markup during render, like Svelte's<svelte:head>. Return{ html, head }:htmlexactly asrenderToString()renders it, andheadfor the document's<head>. A<title>inheadreplaces Farm.js's fallback title, and a route's metadata title still wins over it.generateHydrationScript(): markup your browser runtime needs before it hydrates, such as Solid's hydration bootstrap. Farm.js puts it in the document head. It must return the same string on every call.markFunctionComponent(component): tags a plain function component Farm.js creates, so a renderer whose own components are functions can tell the two apart. See Components.findStaticShellBoundary(chunk): where a streamed chunk stops being static. Partial prerendering caches the HTML before that point as the page's shell. Return the index to cut at, or-1when the chunk is all static. Without this export, the renderer gets no static shell: Farm.js doesn't guess where your dynamic markers start.configureApp(setup): receives the descriptor'sappSetupmodule. Required when the descriptor setsappSetup.capabilities: a copy of the descriptor's capabilities. Farm.js checks that what the module declares covers what the descriptor declares.
withIsland(), wrapClientGraph(), and isolateServerPageGraph() are for islands.
renderServerTreePage() serves React Server Components; leave it out. Farm.js no longer reads an
ErrorBoundary export: a page that throws under an error.* file renders that file as the route's
error page.
The client module
Farm.js's browser entries import the client module by name. Four exports are required:
// src/client.js
import { createRoot as createLeafRoot } from "leaf/dom";
export { Fragment, Suspense, createElement, isValidElement } from "leaf";
export { hydrateRoot } from "leaf/dom";
// A leaf root renders next to what's already in its container, so empty it first.
export function createRoot(container) {
container.replaceChildren();
return createLeafRoot(container);
}createElement()andSuspense: build the route tree in the browser. They must build the same tree the server module built from the same calls, or hydration fails to match.createRoot(container): a root whose first render replaces what's incontainer, as React's does. Farm.js uses it for a route with no server markup to adopt, after a navigation that replaces the root, and whenhydrateRoot()throws. The last two leave markup in the container, so a root that renders next to it shows the page twice.hydrateRoot(container, element, routeState): a root that adopts the server's markup incontainer: the elements already there stay, and gain their event listeners and state. The third argument is the route state described under Route updates.configureApp(setup): required when the descriptor setsappSetup.
If hydrateRoot() throws in development, Farm.js logs
[Farm.js] Hydration error; rendering the page on the client instead: with the error and renders
the route with createRoot(). A production build does the same only when the descriptor sets
capabilities.hydrationFallback: true; otherwise the page keeps the server's markup without event
listeners. With the fallback the page works, but the server's DOM, focus, and typed input are
replaced. Set it once your createRoot() replaces what's in its container, as farm-leaf's does
above.
Both functions return a root:
interface FarmRendererClientRoot {
render(element: unknown): void;
renderRoute?(state: FarmRendererRouteState): void;
unmount(): void;
}render() renders a new tree into the root. Farm.js calls it with the next route's tree on a client
navigation. unmount() removes what the root rendered and stops its updates.
The Vite module
The Vite module exports one function. Farm.js calls it for each graph it builds and adds what it returns to Vite's plugins:
// src/vite.js
import { transformWithOxc } from "vite";
import { compileLeaf, componentName } from "./compile.js";
const JSX = { runtime: "automatic", importSource: "leaf" };
export function createFarmRendererPlugin() {
return {
name: "farm-leaf",
config() {
// Compile JSX against leaf's runtime.
return { oxc: { jsx: JSX } };
},
async transform(code, id) {
const file = id.split("?")[0];
if (!file.endsWith(".leaf")) return null;
// compileLeaf() turns the markup into JSX, which oxc compiles against leaf like any .tsx file.
const source = compileLeaf(code, componentName(file), file);
const result = await transformWithOxc(source, `${file}.tsx`, {
lang: "tsx",
jsx: JSX,
sourcemap: true,
});
return { code: result.code, map: result.map };
},
};
}createFarmRendererPlugin(options) may return a plugin, an array of plugins, or a promise of
either. options holds:
ssr: whether the plugin serves a server graph. A production build creates one plugin for the browser graph (ssr: false) and one for the server graph (ssr: true). Development runs one Vite server for both and passesssr: true, so pick server or browser output per module from thessroption Vite passes totransform().rendererOptions: the descriptor'soptions.buildLifetime: anAbortSignalshared by every graph of one production build, aborted once they all close. Tie a cache shared between the graphs to it, and clear it onabort. Development doesn't pass it.
Hot updates in development
The renderer contract has no hot-update hook: hot updates belong to your Vite plugin. The official
renderers get them from their library's plugin: @vitejs/plugin-vue, vite-plugin-solid,
@sveltejs/vite-plugin-svelte, and @preact/preset-vite. Each accepts an edited component module
and swaps it in place, so the page and its layouts keep their state.
Without that, Vite reloads the page when you save a component, and all component state resets, including the layout's. The leaf example works this way, apart from its islands. Production builds aren't affected.
To add hot updates, have the plugin's transform() append an import.meta.hot.accept() handler to
component modules in the browser graph (ssr false in the transform options) that swaps the new
component into the instances your runtime has mounted. Vite's
HMR API describes the handler.
Islands are the exception, because Farm.js mounts their roots. On a renderer that declares
reconcilesRerenders, when your plugin's output for an island's module has no import.meta.hot
code, Farm.js renders each of that module's islands again with the new module. The rest of the page
keeps its state, and the islands start with fresh state. The page reloads instead when other
browser code imports the module too, or when one of its islands hasn't started yet, since the
server rendered that island's HTML with the old code. Island hot updates ship in the release after
0.1.86.
Streaming
Without streaming, Farm.js renders a page with renderToString() and sends it once the whole page is
ready. With it, the response starts with the first chunk your renderer emits.
Declare each primitive in the descriptor, and export the matching function from the server module:
web: true: exportrenderToReadableStream(element, options). It returns aReadableStreamofUint8Arrayor string chunks, or a promise of one.node: true: exportrenderToPipeableStream(element, callbacks). It returns{ pipe(writable), abort?(reason) }. Callcallbacks.onShellReady()once Farm.js may start piping,onShellError(error)when the render fails before then, andonError(error)for a later error.
capabilities: {
streaming: { node: false, web: true },
reconcilesRerenders: true,
functionComponents: true,
},Farm.js checks both sides when the development server starts and again in the production server: a
descriptor that declares a primitive the server module doesn't export fails with an error that names
it. A renderer that exports only renderToReadableStream() streams in development as well as in
production builds.
A root layout that renders its own <html> streams too. Farm.js holds the output until its <body>
and puts its head assets (stylesheets, metadata, the hydration script) in the layout's <head>, so
the page starts as soon as the shell is ready.
The descriptor's top-level node and web apply to every runtime. When a package's exports change
between runtimes, as React DOM's do between Node and edge builds, override them per runtime:
streaming: {
node: true,
web: false,
runtimes: { edge: { node: false, web: true } },
},Development resolves as node. A production build resolves the runtime from its deployment preset,
and an unknown preset uses the top-level values.
Errors in a stream
The response status goes out with the first chunk, so a render error is handled by when it happens:
- Before any output: fail the stream. Error the
ReadableStream, or callonShellError(). Farm.js answers with the error's status. - After output has started: the status is sent. Report the error through
options.onError()orcallbacks.onError(), then end the stream. Farm.js logs it, and the response ends with what was sent. Erroring a Web stream after output resets the connection in a production build.
Here is a Web stream over a renderer that yields HTML chunks as an async iterator:
// src/server.js
const encoder = new TextEncoder();
export function renderToReadableStream(element, options) {
// renderChunks() is your renderer: an async iterator of HTML strings.
const chunks = renderChunks(element);
let started = false;
return new ReadableStream({
async pull(controller) {
let result;
try {
result = await chunks.next();
} catch (error) {
// Before any output, the error decides the status. After it, the status is already
// sent, so report the error and end the document.
if (!started) return controller.error(error);
options?.onError?.(error);
return controller.close();
}
if (result.done) return controller.close();
started = true;
controller.enqueue(encoder.encode(result.value));
},
cancel() {
return chunks.return?.();
},
});
}What a Suspense boundary does in a stream is up to the renderer. A renderer can flush the HTML
before a boundary and then wait for the content inside it, or send the fallback first
and the content later with a script that swaps it in, as React does.
Client state and hooks
Farm.js keeps its client state in stores any renderer can read. Each implements FarmClientStore:
interface FarmClientStore<TSnapshot> {
getSnapshot(): TSnapshot;
subscribe(listener: () => void): () => void;
}@farm.js/core/renderer-client creates them:
createRendererRouter(options):pathname,searchParams,params,pageState, andnavigation, withpush,replace,refresh,prefetch,back,forward,pushState, andreplaceState.createRendererAction(serverFn, options): a server function call'spending,status,data, anderror, withsubmit(input)andreset().createRendererQuery(query, input, options): a server query'sdata,error,status,pending,fetching, andstale, from Farm.js's shared browser cache, withrefetch()anddispose().createRendererTheme(): the theme preference and resolved theme, withsetTheme()andtoggleTheme().createRendererI18n(): the locale state, a translatort, andsetLocale().createStore(state, actions): the app's own state. See Shared client state.
The official bindings are one function that turns a store into the library's own state, plus thin wrappers. For a library with React-style hooks:
// src/bindings.js
import { useEffect, useMemo, useState } from "leaf";
import {
createRendererAction,
createRendererQuery,
createRendererRouter,
} from "@farm.js/core/renderer-client";
export function useFarmStore(store) {
const [snapshot, setSnapshot] = useState(() => store.getSnapshot());
useEffect(() => {
// Catch a change between the first render and the subscription.
setSnapshot(() => store.getSnapshot());
return store.subscribe(() => setSnapshot(() => store.getSnapshot()));
}, [store]);
return snapshot;
}
export function useRouter(options) {
const [router] = useState(() => createRendererRouter(options));
return { ...useFarmStore(router), push: router.push, replace: router.replace };
}
export function useAction(target, options) {
const [action] = useState(() => createRendererAction(target, options));
return { ...useFarmStore(action), submit: action.submit, reset: action.reset };
}
export function useServerQuery(query, input, options) {
// The browser posts the input, so it's serializable and its JSON identifies a new read.
const observer = useMemo(
() => createRendererQuery(query, input, options),
[query, JSON.stringify(input ?? null)],
);
useEffect(() => () => observer.dispose(), [observer]);
return { ...useFarmStore(observer), refetch: observer.refetch };
}- Create a store once per component, not on every render, and unsubscribe when the component unmounts.
getSnapshot()returns the same value until the state changes, so an identity check is enough to skip an update.- Call
dispose()on a query store when its component unmounts. - On the server, the router store reads the request's URL, so a component renders the same path,
search params, and route params there as in the browser. This ships in the release after 0.1.81;
in 0.1.81 the server snapshot is
/with no params. - On the server, a query store returns an idle snapshot and starts no request. The browser loads the query after hydration.
- A query that is still on the page reads again when an action invalidates its key with
invalidate()from@farm.js/core/cache.
A component then reads them like any other state:
"use client";
import { useAction, useServerQuery } from "farm-leaf/bindings";
import { plantCrop, plantedCount } from "../server/plant";
export default function PlantButton() {
const plant = useAction(plantCrop);
const total = useServerQuery(plantedCount, undefined);
return (
<section>
<button type="button" disabled={plant.pending} onClick={() => plant.submit({ name: "rye" })}>
Plant rye
</button>
{plant.error && <p role="alert">{plant.error.message}</p>}
<p>Planted so far: {total.data?.planted ?? "…"}</p>
</section>
);
}plant.submit() returns a promise that rejects when the call fails, and the error also lands in
plant.error.
Server functions in the browser
A component imports server functions and queries from their server module, as above. With any renderer but React, turn that on in the app's config:
export default defineConfig({
renderer: leaf(),
experimental: { serverActions: true },
});The browser then gets a reference for each server function instead of its code, and a call posts
its input to the current page, whose server runs it. Without the flag, the import stops the build
with CLIENT_SERVER_FUNCTION. See
Native client bindings.
Action forms
To give an action a form, call submitRendererActionForm(action, event) from the form's submit
listener. It cancels the browser's own submission, sends the form's fields and the button that
submitted it as FormData, and resets the form when the call succeeds. A failure leaves the fields
as they were and the error in the action's error. A listener that already cancelled the submission
keeps it cancelled.
submitRendererActionForm is newer than the other stores: it ships in the release after 0.1.81.
Links
Farm.js's router handles a click on any anchor with a data-farm-link attribute, and prefetches as its
attributes say. A Link only renders those attributes, which resolveLinkAttributes() computes from
the same options React's Link takes:
// src/bindings.js
import { createElement } from "leaf";
import { FARM_LINK_OPTION_KEYS, resolveLinkAttributes } from "@farm.js/core/renderer-client";
export function Link(props) {
const options = {};
const anchor = {};
for (const [name, value] of Object.entries(props)) {
if (FARM_LINK_OPTION_KEYS.includes(name)) options[name] = value;
else anchor[name] = value;
}
return createElement("a", { ...anchor, ...resolveLinkAttributes(options) });
}resolveLinkAttributes() applies route params, query, hash, the locale, the trailing-slash
preference, and the base path to href, and adds the prefetch, replace, scroll, and
viewTransition attributes. Type the props with FarmLinkOptions from the same entry to check
href against the app's routes.
Images
@farm.js/core/image is React's Image. An Image of your own renders an <img> with the
attributes resolveImageAttributes() returns. It takes the same options and loads no UI library.
The attributes use the names createElement() takes: srcSet, fetchPriority, and a style
object with camelCased keys.
// src/bindings.js
import { createElement } from "leaf";
import { resolveImageAttributes } from "@farm.js/core/renderer-client";
export function Image(props) {
return createElement("img", resolveImageAttributes(props));
}It sizes src and srcSet to images.deviceSizes and images.imageSizes through Farm.js's image
endpoint, lazy-loads by default, and adds the blur placeholder for placeholder: "blur". preload
sets loading="eager" and fetchPriority="high"; React's Image also preloads the file, which a
renderer without preload() skips. resolveImageAttributes ships in the release after 0.1.86.
Your own file format
A renderer with its own component format, like .vue or .svelte, does two things:
- Lists the extension in
componentExtensions, so Farm.js discoverspage.leafandlayout.leafas routes. - Compiles the format to a JavaScript module in its Vite plugin, with the component as the default export, as the Vite module above does.
The example's .leaf files are HTML with {{ values }}, @event handlers, and <leaf:if> and
<leaf:for> tags. farm-leaf/src/compile.js turns that markup into JSX:
<script module>
export const hydrate = true;
</script>
<script>
import { useState } from "leaf";
const [count, setCount] = useState(0);
</script>
<button @click="setCount((n) => n + 1)">Clicked {{ count }} times</button>
<leaf:if test="count > 3">
<p>That's a lot of clicks.</p>
</leaf:if>Throw from the plugin when a file can't compile, with the file, the line, and the fix in the
message. farm build fails with that message, and farm dev logs it and answers the page with a 500.
Farm.js plans what hydrates before your compiler runs. From each page, layout, and module they import,
it reads "use client", the hydrate and island exports, the imports, and the props a page
passes to each client component. Give the descriptor compile() and Farm.js reads a file in your
format as the module it compiles to:
// src/index.js
import { compileLeaf, componentName } from "./compile.js";
// in defineRenderer({ ... })
compile(source, file) {
return compileLeaf(source, componentName(file), file);
},Return the same module your Vite plugin compiles the file to, with any "use client" as its first
statement. Farm.js calls compile() only for files with your componentExtensions, and only reads
what it returns; your Vite plugin still compiles the file for the build. When it throws, the scan
fails with your message and the file.
Without compile(), Farm.js reads the file as written. A page or layout can still say whether it
hydrates with a literal hydrate export, but a component in your format can't be a client
component, so it never becomes an island:
<script module>
export const hydrate = true;
</script>To give the format a syntax of its own for hydration, read it in hydration.resolve(). See
Hydration.
Route files
Farm.js's folders decide routes by default: about/page.leaf is /about, and layout.leaf lays out
its folder. When your library has another convention, give the descriptor a routes() method. It
returns a resolver, and Farm.js calls it once per file:
// src/index.js, in defineRenderer({ ... })
routes({ defaults }) {
const url = (segments) => `/${segments.join("/")}`;
return {
resolve(file) {
// Farm.js's folders keep working next to the flat files.
const folderRoute = defaults.resolve(file);
if (folderRoute || file.segments[0] !== "guides" || file.extension !== ".leaf") {
return folderRoute;
}
if (file.name === "_layout") return { kind: "layout", pattern: url(file.segments) };
if (file.name.startsWith("_")) return null;
const name = file.name.replace(/\.client$/, "");
return {
kind: "page",
pattern: url(name === "index" ? file.segments : [...file.segments, name]),
...(name === file.name ? {} : { hydrate: true }),
};
},
};
},src/app/guides/
_layout.leaf layout of /guides
index.leaf /guides
[crop].leaf /guides/[crop]
watering.client.leaf /guides/watering, hydrates
_tip.leaf not a route: a component index.leaf importsroutes(context) may be async. Farm.js calls it when farm dev starts and again when a file under
its directory is added or removed, in every farm build, and in farm generate. It gets:
root: the project root, or a layer's root when the app extends one. Farm.js scans each.defaults: Farm.js's folder rules as a resolver over the same directory. Returndefaults.resolve(file)for a file to keep them.
It returns:
dir: the directory to scan, relative toroot. Defaults tosrc/app(<srcDir>/app), and must stay inside the project.resolve(file): called for each file underdirwith a component extension (.ts,.tsx,.js,.jsx, and yours),.md, or.mdx, in sorted order. Return a route, ornullwhen the file isn't one.
The file Farm.js passes, for src/app/guides/watering.client.leaf:
| Field | Value |
|---|---|
path | "guides/watering.client.leaf", with / on every system |
segments | ["guides"] |
name | "watering.client" |
extension | ".leaf" |
The route you return:
| Field | Value |
|---|---|
kind | "page", "layout", "loading", "error", or "not-found" |
pattern | The URL in Farm.js's folder syntax: "/", "/blog/[slug]", "/docs/[...path]" |
hydrate | Optional. Whether the file hydrates; see Hydration |
strategy | Optional. When it hydrates: "load", "idle", "visible", or "interaction" |
A rule Farm.js can't serve fails the scan with the file's path and the fix:
patternmust start with/, and can't have an empty,.,.., or@namesegment, or a\,?, or#.not-foundonly takespattern: "/". Farm.js renders one not-found page.- Two files can't map to the same kind and pattern. The error names both.
- A
resolve()that throws fails the scan, naming the file it was resolving.
Some files stay with Farm.js. It finds route.ts handlers, middleware, instrumentation, metadata
files (sitemap, robots, manifest, llms, opengraph-image, twitter-image), and named slots
(@name folders) in src/app as before, and never passes them to resolve().
Generated route types follow the same rules, so farm generate lists /guides/watering and a
Link to it type-checks.
Hydration
Farm.js decides whether each page and layout hydrates before your compiler runs. The descriptor's
hydration sets what applies when a file says nothing, and can read your format's own syntax:
// src/index.js, in defineRenderer({ ... })
hydration: {
pages: false, // the default: a page that says nothing renders on the server only
layouts: false,
strategy: "visible", // when a hydrating page or layout loads, unless it says
// `// @hydrate`, `// @hydrate idle`, or `// @hydrate false` in a .leaf file's module script.
resolve(source) {
const pragma = /^\s*\/\/ @hydrate(?: (load|idle|visible|interaction|false))?\s*$/m.exec(source);
if (!pragma) return undefined;
if (pragma[1] === "false") return { hydrate: false };
return pragma[1] ? { hydrate: true, strategy: pragma[1] } : { hydrate: true };
},
},For each page and layout, the most specific setting wins:
- The file.
"use client",export const hydrate,export const island, or whathydration.resolve()reads."use client"always hydrates. - Its route rule. The
hydrateandstrategythatroutes()returned for it. - The renderer's defaults.
hydration.pagesorhydration.layouts, andhydration.strategy. - Otherwise the file renders on the server only.
resolve(source, file) gets the file as written, before compile(), and only for files with your
componentExtensions. .tsx and the other built-in extensions keep Farm.js's reading. Return
{ hydrate?, strategy? }, or nothing to leave the file to Farm.js. When a file both exports hydrate
or island and uses your syntax, and the two disagree, the scan fails and names the file: keep one.
A route's page and the hydrating layouts above it hydrate as one root, so they share one strategy.
When they declare different ones, or a hydrating layout declares none, the route hydrates on
"load".
Components
Plain function components
Some components Farm.js renders aren't written for your library, such as integration provider
components. They're plain functions: they take props and return an element tree. Set
capabilities.functionComponents: true once your renderer calls such a function and renders what
it returns, on the server and in the browser. Farm.js renders
integration provider components only when the renderer declares it, and otherwise fails with an
error that names the renderer.
If your library's own components are functions too, as compiled Vue and Svelte components are,
export markFunctionComponent(component) from the server module. Farm.js calls it on those plain
functions; call the marked ones, and instantiate every other function as one of your own
components.
Async components
Farm.js awaits an async page itself with every renderer but React, in development and in production
builds, and renders the elements it returns. That's how page.md pages render with every renderer.
Inside the tree, async components are the renderer's choice. A renderer that doesn't support them
must reject them with an error that says so, instead of rendering a promise, an empty string, or
[object Object]. A streaming renderer can wait for them in the stream and still reject them in
renderToString().
Route updates
capabilities.reconcilesRerenders states what root.render(nextTree) does to what's mounted:
true: the root compares the new tree with the live DOM, like React, Preact, and Vue. A client navigation that keeps the same layout keeps its DOM nodes, focus, and component state.false(the default): the root rebuilds the tree. Farm.js doesn't rely on reconciliation it won't get.
A fine-grained renderer with no virtual DOM can keep layouts mounted another way: give the root a
renderRoute(state) method. Farm.js calls it instead of render() on a client navigation, and passes
the same state as the third argument of hydrateRoot():
interface FarmRendererRouteState {
element: unknown; // the whole tree, for a root that only implements render()
layouts: readonly { pattern: string; Component: unknown }[]; // outermost first
page: unknown; // what goes in the innermost layout's slot
params: Readonly<Record<string, string>>;
wrap?: (element: unknown) => unknown; // Farm.js's outer wrappers, such as integration providers
}The official Solid renderer keeps the layouts whose pattern matches mounted and updates the page
slot and params through signals. See Re-render behavior.
Islands
With serverComponents: { mode: "islands" }, pages render on the server only, and a
client component rendered from one hydrates on its own, as an island, instead of hydrating the
whole route. A renderer opts in with capabilities.islands: true and one server export,
withIsland(). On a renderer that doesn't, that config fails farm dev and farm build. It writes no browser code:
Farm.js's island runtime hydrates each island with the client module's createElement() and
hydrateRoot(), and calls unmount() on its root when a navigation removes it.
// src/server.js
import { resolveFarmIsland } from "@farm.js/core/renderer";
import { Fragment, createElement } from "leaf";
const withoutClientAttributes = (props) =>
Object.fromEntries(Object.entries(props).filter(([key]) => !key.startsWith("client:")));
function script({ attributes, text }) {
// `text` is escaped for a script element already: write it raw.
return createElement("script", { ...attributes, dangerouslySetInnerHTML: { __html: text } });
}
export function withIsland(component, reference) {
if (typeof component !== "function") return component;
return function Island(props) {
const island = resolveFarmIsland(props, reference);
if (!island) return createElement(component, withoutClientAttributes(props));
return createElement(
Fragment,
null,
...island.values.map(script),
createElement(
island.element.tag,
island.element.attributes,
createElement(component, island.props),
),
script(island.script),
);
};
}withIsland(component, reference): Farm.js wraps each export of a"use client"module with it in the server graph.referenceis{ src, export, strategy }: the module the browser imports, the export, and the module'sislandstrategy. Return a value that isn't one of your components as it is.resolveFarmIsland(props, reference): the parts to write, for the props the component got where it's used. Writevaluesfirst, thenelementwith the component inside, rendered withisland.props, thenscript. Attributes are unescaped; escape them as you write any attribute. It returnsundefinedwhen a prop can't reach the browser, such as a function that isn't a server action. Farm.js logs which prop, once; render the component without an island, and its server HTML stays without client code.
An island starts when its strategy says: load, idle, visible, or interaction. A module's
export const island = "idle" sets the default for its components, and a client:* attribute
sets it where one is used:
<Counter label="Plant" client:visible />resolveFarmIsland() removes client:* from the props, and throws for an attribute that isn't a
strategy, has a value, or is one of two on the same element. Type the attributes by extending your
JSX namespace's IntrinsicAttributes with FarmIslandAttributes:
// src/index.d.ts
import type { FarmIslandAttributes } from "@farm.js/core/renderer";
declare module "leaf/jsx-runtime" {
namespace JSX {
interface IntrinsicAttributes extends FarmIslandAttributes {}
}
}Props go through the same codec as islands mode: JSON values, Date, Map, Set, BigInt, typed
arrays, and server actions. A value several islands of one response share is sent once.
A layout with "use client" hydrates as one root, and keeps a server page under it as HTML. Two more
server exports tell your withIsland() which is which, with the same element in and out:
wrapClientGraph(element): Farm.js wraps a tree that hydrates as one root. A client component inside it is part of that root: render it plain, without an island.isolateServerPageGraph(element): Farm.js wraps a server page such a root keeps as HTML. Client components inside it are islands again.
A context your withIsland() reads is enough; the leaf example's farm-leaf/src/server.js uses
one. Farm.js starts the page's islands after the layout's root renders a navigation, and unmounts
the ones whose markup it replaced.
A client component in your own format is an island too when the descriptor has compile(): Farm.js
finds its "use client" in the module compile() returns. In the leaf example,
src/components/planter.leaf puts it first in its module script, and src/app/islands/leaf/page.leaf
renders two:
<script module>
"use client";
export const island = "load";
</script>
<script>
import { useState } from "leaf";
const [planted, setPlanted] = useState(0);
</script>
<button @click="setPlanted((n) => n + 1)">{{ props.crop }} planted: {{ planted }}</button>farm dev and farm build fail when the descriptor declares islands and the server module
doesn't export withIsland.
Test a renderer
Type-check the modules
Assign each module to its contract type. A module that drifts from what Farm.js imports then fails type-checking:
// test/contract.ts
import type {
FarmRendererClientModule,
FarmRendererServerModule,
FarmRendererViteModule,
} from "@farm.js/core/renderer";
import * as client from "../src/client.js";
import * as server from "../src/server.js";
import * as vite from "../src/vite.js";
export const serverContract: FarmRendererServerModule = server;
export const clientContract: FarmRendererClientModule = client;
export const viteContract: FarmRendererViteModule = vite;The module types were FarmServerRendererRuntime and FarmRendererClientRuntime before. Both
names still work, as deprecated aliases.
Run the conformance suite
@farm.js/renderer-tests is the suite Farm.js runs against its official renderers. It calls your
modules the way Farm.js does, in Node and jsdom, and fails where your renderer behaves differently:
pnpm add -D @farm.js/renderer-tests vitest jsdom// test/server.test.js
// @vitest-environment node
import { testDescriptor, testServer } from "@farm.js/renderer-tests";
import { leaf } from "../src/index.js";
import * as server from "../src/server.js";
testDescriptor({
name: "leaf",
createDescriptor: leaf,
expected: { vite: "farm-leaf/vite", server: "farm-leaf/server", client: "farm-leaf/client" },
});
testServer(server);// test/client.test.js
// @vitest-environment jsdom
import { testClient } from "@farm.js/renderer-tests";
import * as client from "../src/client.js";
import * as server from "../src/server.js";
testClient({
name: "leaf",
client,
server,
// The value the descriptor declares in capabilities.reconcilesRerenders.
reconcilesRerenders: true,
});A renderer that declares islands, or reads its own file format, runs two more. List files in
your format with what each hook should say about them; a hook you don't have, or a field a file
leaves out, is skipped:
// test/server.test.js
import { testIslands, testSource } from "@farm.js/renderer-tests";
testIslands({ name: "leaf", server });
testSource({
name: "leaf",
createDescriptor: leaf,
files: [
{ path: "src/app/guides/index.leaf", route: { kind: "page", pattern: "/guides" } },
{ path: "src/app/guides/_tip.leaf", route: null },
{
path: "src/app/guides/harvest.leaf",
source: "<script module>\n // @hydrate interaction\n</script>\n",
route: { kind: "page", pattern: "/guides/harvest" },
hydration: { hydrate: true, strategy: "interaction" },
},
{
path: "src/components/planter.leaf",
source: '<script module>\n "use client";\n</script>\n<button>Plant</button>\n',
client: true,
},
],
});Both ship in the @farm.js/renderer-tests release after 0.1.0-beta.3.
testDescriptor: the descriptor names all three modules and returns fresh arrays on each call.testServer: element primitives, escaping, React-style props, function components, async components, error boundaries, and shell errors in each stream you export.testClient: the exports Farm.js imports, mounting and updating a root, events, and hydrating in place.testServerQuery: a server render never shares the browser query cache between visitors.testNativeTree: the mobile native tier reads your server markup like any other renderer's.testIslands:withIsland()writes an island with its source, export, strategy, and props script, keeps the server HTML when a prop can't reach the browser, andwrapClientGraph()andisolateServerPageGraph()turn islands off and on again.testSource:routes()maps each file to the route you expect, with a pattern Farm.js can serve;hydration.resolve()reads each file's settings; andcompile()returns a module with"use client"where Farm.js looks for it. Each answers the same way every time.
The suite doesn't start an app. Run one on your renderer in farm dev and in a production build
too: the example's Playwright tests run the same checks against both.
Limits
- One renderer per app.
rendereris app-wide, so every page and layout uses the same one. - Route rules cover pages, layouts, and their boundaries. API routes, middleware, metadata
files, and named slots stay in
src/appfolders. - React Server Components are React-only.
{ mode: "rsc" }runs React's Flight pipeline. On another renderer,{ mode: "islands" }gives server-only pages and islands, without React's async server components or server trees. - Islands take data. An element passed as
childrenor another prop, or a promise, can't reach the browser, so that island keeps its server HTML without hydrating. Integration providers don't wrap islands. - Some UI integrations are React-oriented. Most integration UI providers render React
components today.
withDocs()builds docs pages with your renderer, and@farming-labs/farmjs/testingchecks that it writes and hydrates them; see Docs adapters on any renderer. - No static shell without
findStaticShellBoundary(). Partial prerendering needs it to know where the dynamic part of a streamed page begins. - React hooks from core throw.
useRouter(),usePathname(), anduseSearchParams()from@farm.js/core/navigationare React hooks. Read the route through your bindings instead.notFound(),redirect(), andpermanentRedirect()from the same entry work with every renderer.
Render Farm.js pages with a UI library of your own: the renderer descriptor, its server, client, and Vite modules, streaming, client hooks over Farm.js's stores, a Link, file formats, route files, hydration, and the conformance suite.