Duolith docs

0163. A server companion renders on request only what the build cannot write

  • Status: Accepted (Mik, 18 Nov 2026)
  • Date: 2026-11-18
  • Decided by: Mik asked for it on 18 Nov 2026 ("a config that generates the most performant version of the server and a pre built docker file … and dev tooling with hmr, just like Svelte has SvelteKit"); the design below is the integrator's, approved by Mik on 18 Nov 2026 with the answers recorded at the end.
  • Planning item: none (after version 1: "per-page rendering modes (37)", "middleware (39)", "server-side queries (8)" and "server functions investigation" in docs/plan/post-v1.md)

Context

Version 1 is client-only, with no server runtime (decision of 13 Nov 2026), and stays so. A web build is static files on any host. Decision 0162 makes those files fast: each route without parameters is written as HTML at build time, and ships script only where it runs (written, islands and app routes).

What a static host cannot do:

  • Routes with parameters (/post/[id]) and pages whose first screen depends on data have no HTML until script runs.
  • Data that changes must be rebuilt and redeployed, or fetched by the browser after the runtime starts.
  • Per-user pages (an account page, a dashboard) can only be written by the browser.
  • Secrets cannot be used by a page at all, because everything a page holds ships to the browser (decisions 0021 and 0105).

Next.js and SvelteKit answer this with a server that renders pages on request (SSR), keeps rendered pages and renders them again in the background (ISR), and renders a route the first time it is asked for and then keeps it (incremental generation). They also run page code on the server, which is where most of their security problems come from: secrets imported into client code, per-user pages stored in a shared cache, state serialized into markup, and server functions callable from any site.

Mik's priorities (18 Nov 2026): as light and fast as possible, and no security holes in the compiled output. His stack runs Bun (see IDX-Studios/work-stable-api).

Decision

An optional extension, the server companion, in its own package (@duolith/server) and its own emitter crate (crates/emit-server). A project without server: in duolith.yaml builds exactly as today. With it, duolith build also writes a server, and duolith dev serves through it.

1. The build decides when each route's HTML is made

The compiler already decides how much script a route ships (decision 0162). With a server it also decides when the route's HTML is made, from what the route reads. The author never picks a mode; they say how fresh data must be, and the build report names each route's mode and why.

ModeWhen the build picks itWhat happens on a request
WrittenThe route reads no server data and no request (0162's three kinds)Served as a file. The server is never involved, so a CDN serves it.
Kept (ISR and incremental generation)It reads server data, but nothing from the request except its own parametersRendered on first request and kept in the server's cache; served from there until it is older than its fresh: time or a key it loaded is invalidated, then served once more while it renders again in the background. A list of parameters given at build time renders those ahead. fresh: forever keeps a page until a key it loaded changes.
Per request (SSR)It reads the request: cookies, headers, the session, or search parameters it does not declareRendered for each request, streamed, and never stored in a shared cache.

One vocabulary for freshness across the whole stack: a page is kept under the keys of the loaded state it read (state.load("posts", …)), the same keys the browser's data core already caches and invalidates by (decisions 0019, 0020). action({ invalidates: ["posts"] }) and a signed POST /_duolith/invalidate with { keys: ["posts"] } both mark every kept page that read "posts" stale. Nothing new to name. With domains (decision 0164) the keys are not typed at all: they are derived from the models a loader returns, and a command's changes: marks the pages stale.

2. Server code lives in server files, and the compiler keeps it there

  • A page's own script never runs on the server. Its first screen is written from first values, as decision 0162 item 3 does at build time, plus the values its loaders return.
  • Server loaders live in a file beside the page, post/[id].server.ts, and are handed to state.load like any loader: state.load(["post", id], loadPost). In the page's browser module the compiler replaces the import with a typed call to the server (/_duolith/load/<route>/<name>), so the page cannot hold server code even by mistake. Any other use of a server file's export in a page or component is an error, as is importing a server file from a file the browser loads.
  • Or in a server block inside the page (Mik, 18 Nov 2026: both). A page may hold a second fenced block, --- server, after its script. The compiler splits it out into the same server module a .server.ts file would make, under the same rules: its exports can only be handed to state.load or action, it is never part of the page's browser module, and the build fails if any of its text, or a value only it reads, appears in a browser file. A page has a server block or a server file, not both, and the block is TypeScript only.
  • Or in Rust, for the Axum target: post/[id].server.rs holds the same loaders as async fns whose return types derive Serialize. The build writes their TypeScript types from the Rust ones, so a page's state.load is checked against them as it is against a .server.ts loader. A project's server files are all TypeScript or all Rust, matching its target.
  • What a loader returns crosses to the browser, so its type must be data: no functions, class instances, symbols or undefined in records. The type check proves this, and an argument that is not is an error.
  • Private environment values (any name in duolith.env without DUOLITH_PUBLIC_) are readable only in server files, through a typed serverEnvironment(). Reading one elsewhere is an error, and the build also searches every browser file for every private value and fails if one appears.
  • The request is read through one typed object (request.cookie("session"), request.header("accept-language")). Reading it is what makes a route per-request, so a route that reads a cookie cannot be kept in a shared cache: the mode follows from the read, and asking for fresh: on such a route is an error.

3. Rendering is string building, compiled from the same template

A server renders by joining strings, not by running the browser runtime against a fake DOM. emit-server compiles each file's folded web template (the one 0162 writes at build time) into a render function, in JavaScript for the JavaScript targets and in Rust for Axum: the parts known at build time are fixed strings, and only the holes (a loaded value, a parameter) are worked out per request, each through one escaping function. There is no virtual DOM, no DOM library and no second renderer to drift: the 0162 invariant "the written HTML equals the built screen" is extended to "equals what the server writes", with the same browser test.

  • All loaders of a route start at once. The compiler knows every loader of the page and its layouts, so there are no waterfalls: the server starts them together as the request arrives, and shares one call per key within a request.
  • The head goes out first. The server sends the document head (styles, module preloads, the import map) before any loader answers, then each part of the screen as its data arrives. A <boundary> (decision 0057) is where the stream may pause: its skeleton is written first and replaced in order when its data comes.
  • The browser picks up where the server left off. What loaders returned goes in one <script type="application/json"> block, escaped so that <, >, & and line separators cannot end it, read with JSON.parse and placed into the data core under its keys. It is never executed and never evaluated, so the Content-Security-Policy keeps script-src closed. The data core then refreshes it in the background as it does today, so the first screen shows at once and stays current.

4. The server is generated, small and dependency-free

duolith build writes dist/server/. For the JavaScript targets it is one module holding a standard fetch(request) → response handler, the route table compiled to a matcher, the render functions and the loaders, with no npm dependencies at run time (no Express, no Elysia). For Axum it is a generated Cargo crate: an axum::Router with the same routes, render functions and cache, and the app's Rust loaders, built to one release binary. Either way, what runs in production is our code and the app's.

# duolith.yaml
server:
  target: bun          # first: bun | node | cloudflare | axum | vercel; later: deno | netlify | lambda
  stores: { pages: { use: memory } }   # kept pages follow the store rules of decision 0165
  fresh: 60s           # default freshness for kept routes; a loader may say its own
  docker: true         # also write a Dockerfile (section 6)

Each JavaScript target is a thin adapter that hands the platform's request to the handler, which is the same on all of them; Axum is the same routes and rules written as Rust. What the config tunes is what the target does well: Bun.serve, Node's http with keep-alive, a Cloudflare Worker's Cache API and KV for kept pages, and for Axum a Tokio runtime with Tower's compression and timeouts and no garbage collector. Built in, with nothing to configure:

  • static files precompressed at build (Brotli and gzip), with the immutable cache headers of decision 0107, served before any route is matched;
  • 103 Early Hints with the route's module preloads where the target supports it;
  • an ETag on every kept and written response, and 304 on a match;
  • graceful shutdown on SIGTERM: stop accepting, finish what is running, then exit;
  • a health route, /_duolith/health, that touches no loader.

Vercel (Mik asked on 18 Nov 2026) is a target that uses the others' output, not a new server. target: vercel writes Vercel's Build Output API folder (.vercel/output), so a deploy needs no framework preset and no build step on Vercel's side:

Our modeOn Vercel
Written routes and static filesstatic/, served by Vercel's CDN. The Content-Security-Policy, security headers and immutable cache headers are written into config.json, because Vercel does not read _headers.
Kept routesPrerender functions: Vercel's own ISR keeps each page at the edge for its keep time. A command's changes: and /_duolith/invalidate call Vercel's on-demand revalidation with the project's bypass token, so the keys still decide. Paths given at build are written ahead as the function's fallback.
Per-request routes, loaders, actions and domainsOne Node function holding the same handler as the Node target, streaming. server: edge: true puts it on Vercel's Edge runtime instead, using the Workers-style handler built for Cloudflare.
StoresThe store rules as everywhere; pages resolves to Vercel's cache, and the rest to a store the app names (Redis, Postgres), since functions share no memory.

Per-user pages keep Cache-Control: private, no-store, so Vercel's CDN never stores them. The conformance suite that compares the four targets also runs against the Vercel output, in Vercel's local build runner.

Without a server, web: host: vercel writes the same folder with only static/ and config.json, so a version 1 site deploys to Vercel with its headers intact.

5. Secure by construction, each rule a test

  • No raw HTML. There is no way to write markup from a value; every hole is escaped by the one writer, text and attributes alike. Links and redirects go through the runtime's address check (no javascript:), and a redirect to another site must be to an origin listed in duolith.yaml.
  • Per-user pages never reach a shared cache. Per-request responses carry Cache-Control: private, no-store and Vary: Cookie. A kept page's cache key is its path and its declared search parameters only, so an extra parameter or header cannot poison it.
  • The host is not trusted. Absolute addresses come from web: url: (decision 0162), never from the Host header.
  • A nonce per response. Decision 0150 could not use a nonce without a server; server-rendered routes now get one, so their policy can list no hashes at all. Written routes keep their hashes.
  • Every call runs the request pipeline of decision 0165 (limits, caller, allow rules, validation, one error shape, logging), compiled per route.
  • Calls into the server are checked. Every /_duolith/load/… and action call validates its arguments against the loader's types (validators generated at build, not a schema library at run time), checks Origin against the site's own, and has a body limit and a timeout. Errors in production show an id, never a stack.
  • Security headers on every response: Strict-Transport-Security, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, frame-ancestors 'none', and Cross-Origin-Opener-Policy: same-origin.

6. A Dockerfile that starts from a hardened base

With docker: true, the build writes a two-stage Dockerfile and .dockerignore beside dist/:

  • Build stage: our own published build image (duolith and its Node companions, pinned by digest) runs duolith build.
  • Run stage: a distroless image of the target's runtime (for Bun, oven/bun:distroless; for Node, distroless/nodejs; for Axum, distroless/static holding one statically linked binary of a few megabytes), pinned by digest, holding only dist/. No shell, no package manager, a non-root user, and a read-only file system except the cache folder when cache: file. Because the server has no dependencies there is no npm install in the image.

The base images are ours to publish and update (ghcr.io/idx-studios/duolith-build and …/duolith-server), with an SBOM and a signature, so an app's Dockerfile is a few lines and a security fix to the base reaches every app on rebuild.

7. Development: one command, with hot module replacement

duolith dev keeps its single command. With server: it runs the generated handler in the target's runtime as a child process (for Axum, cargo rebuilds the server crate when a .server.rs file changes) and sends page requests to it, so development renders exactly as production does. Today duolith dev reloads the whole page after each rebuild; with this extension, for every project, with or without a server, it replaces modules in place:

  • A page, layout or component changed: the dev server rebuilds that file only and sends its address down the existing reload channel. The runtime imports the new module and builds that screen again, keeping the value of every state(...) whose name and type did not change (the compiler knows both). The router, the stack and every other screen stay as they are.
  • A style changed: the stylesheet is swapped, with no screen rebuilt.
  • A server file changed: the server reloads that module, and the pages that loaded from it fetch again.
  • Anything the runtime cannot swap safely (the route table, duolith.yaml, a state whose type changed) falls back to a reload of that screen, then of the page, and says why in the console.

The native dev server (decision 0141) gets the same messages over its socket.

8. What the browser and the app gain without a server

The first stage needs no server and helps every static site and every native app; the server companion is built on it. Decision 0162 does not cover it, so it is this record's stage 1:

  • Build-time data: a loader marked to run at build fills a written route's first screen with real content, and paths() beside a route with parameters lists the addresses to write.
  • Seeds: what those loaders returned ships as a seed file for the data core (a separate file from the app's own origin, never inline), on the web and inside the native bundle, so an app's first screen shows real data at once and refreshes in the background.
  • Incremental rebuilds: duolith build writes again only the routes whose files or data changed.

Stages

Stages 1 and 2 need no server, so they are part of version 1, which stays client-only (Mik, 18 Nov 2026). The rest follows version 1.

  1. In version 1: build-time data, seeds and incremental rebuilds (section 8).
  2. In version 1: hot module replacement in duolith dev (section 7).
  3. crates/emit-server, the handler, kept and per-request routes, streaming, and the first targets together (Mik, 18 Nov 2026): Bun, Node, Cloudflare Workers (with the Cache API and KV), Axum, and Vercel's output built from the Node and Workers handlers. One conformance suite runs every route of every example against all of them and compares their responses byte for byte.
  4. Server loaders and actions in TypeScript and Rust, private environment values, the generated validators.
  5. The Dockerfile and the published base images.
  6. Later targets: Deno, Netlify and Lambda.

Each stage has a brief, a benchmark against the written route it replaces, and the security rules above as tests.

Alternatives considered

OptionWhy not
Run the browser runtime on the server against a DOM libraryA DOM library in every server, several times slower than joining strings, and a second way to make the same HTML
Run each page's whole script on the server, as Next.js and SvelteKit doPage code would run in two places, and anything it imports could reach the browser; the classic way secrets leak. Loaders in server files keep the boundary in the compiler
Only a Rust server, running TypeScript loaders in an embedded JavaScript engineA JavaScript engine inside every server, and no JavaScript edge platform. Axum is one target among four, with loaders written in Rust
Only JavaScript serversLeaves out the fastest and smallest server an app can have, and teams that write their back end in Rust
Build on Elysia, Hono or ExpressA framework dependency in every server, its own router beside ours, and its release cycle. The handler needs a router, a cache and headers, which the build generates
Let the author choose SSR, ISR or static per routeThe compiler can prove which one a route needs, and a hand-picked mode can be wrong in the dangerous direction (a per-user page in a shared cache)
Serialize loaded data with a format that keeps dates, maps and functionsNeeds evaluation or a decoder that can be tricked; plain JSON in a non-executing block is read with JSON.parse only
A separate request for the data instead of the JSON blockA round trip before the first screen can take over, for no gain in safety once the block cannot be executed
Put the server itself in version 1Reverses the 13 Nov decision and doubles the security surface before the client is finished

Consequences

  • Version 1 stays client-only and gains stages 1 and 2, which make static sites and apps faster. A project with no server: pays nothing for the rest.
  • New contexts in tools/boundaries.yaml: crates/emit-server (reads the analyzer and emit-web's templates) and packages/server (the handler, cache and targets; it may not depend on packages/client's browser modules).
  • New language and schema surface, each with its spec entry, reference page, diagnostic codes and fixtures: server files and the --- server block, and what may import them, serverEnvironment(), the typed request, fresh:, paths(), and the server: group in spec/schemas/project.schema.json.
  • The invariant "the written HTML equals the built screen" (0162) now covers three writers: build, server and browser. One browser test compares all three for every example.
  • We publish and maintain two container images, with their digests updated by a scheduled job. Publishing needs Mik's registry account.
  • The build report gains each route's mode and the reason, next to its kind.
  • docs/plan/post-v1.md's Web and Data items 8, 37 and 39 are answered here once this is accepted.

Mik's answers (18 Nov 2026)

  • The first targets are Bun, Node, Cloudflare Workers and Axum, built together.
  • Vercel is supported from the start, through its Build Output API; static sites deploy there in version 1 with web: host: vercel.
  • Server code may live in a .server.ts (or .server.rs) file beside the page, or in a --- server block inside it.
  • Stages 1 and 2 (build-time data, seeds, incremental rebuilds, hot module replacement) are in version 1; the server follows it.