SSR / foldkit-host
host
A server for a Foldkit Plus application handles four kinds of requests: built
static assets, sign-in routes (/auth/…), data requests (/remote), and
server-rendered pages. Writing that routing table twice — once for a Cloudflare
Worker and once for a local Node server — risks subtle drift in origin checks,
streamed body cancellation, or how index.html and its build id are loaded.
foldkit-host gives you small, composable parts for your own fetch handler: a
per-isolate initializer (Host.isolate), a cached page template loader
(Host.template), an origin-checked route dispatcher (Host.routes), and a
Node http adapter (Host.node) that runs the same handler locally.
See all of them wired together in
examples/reference/src/worker.ts.
Install
pnpm add foldkit-hostPeers on foldkit (for resolveRequestUrl).
A first Worker
This creates a Worker handler that serves /assets/ from Cloudflare Assets,
requires env.ORIGIN to be set for every other route, answers /health, and
falls back to the built index.html:
import { Host } from 'foldkit-host'
interface Env {
readonly ASSETS: Host.Assets
readonly ORIGIN?: string
}
const template = Host.template((env: Env) => env.ASSETS)
export default {
fetch: Host.routes({
origin: 'ORIGIN',
assets: { at: '/assets/', binding: (env: Env) => env.ASSETS },
routes: {
'/health': async () => new Response('ok'),
},
otherwise: async (_request, env) => {
const { html } = await template(env)
return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } })
},
}),
}A request to /assets/app.js serves the asset even before ORIGIN is set. A
request to /health returns 200 ok once ORIGIN is configured (or 500 with
Set ORIGIN to where this application is served. if unset). Any other path reads
/index.html once via template(env) and returns it as HTML.
Host.template(binding)declares the template read; the first request loads/index.htmland its build id from the binding and shares that result across later requests. A missing file or missing build id rejects, so the next request retries.Host.routes(config)returns the Worker'sfetchhandler. Paths ending in/match prefixes ('/auth/'); other paths match exactly ('/remote'). Routes run in the order written, so put more specific paths first.origin: 'ORIGIN'checks thatenv.ORIGINis a non-empty string on every non-asset request. Insideroutesandotherwise,env.ORIGINis narrowed tostring. Withoutassets, pass type parameters explicitly:Host.routes<Env, 'ORIGIN'>({ … }).