Duolith docs

Build-time data

A page can load its data while the app is built. Its first screen is then written with real content, which shows before any script runs, and the app refreshes the data in the background once it is old enough. examples/data has both kinds of page: pages/built.duo and pages/post/[id].duo.

Loading at build

Write the loader in a behaviour file and pass at: "build":

// behaviours/posts.behaviour.ts
import { api, environment } from "@duolith/client";
import type { Post } from "../api/posts.ts";

const settings = environment({ apiUrl: "https://api.example.com" });

export function loadPosts(): Promise<Post[]> {
  return api(settings.apiUrl).get<Post[]>("/posts");
}
---
import { state } from "@duolith/client";
import { loadPosts } from "../behaviours/posts.behaviour.ts";

const feed = state.load("posts", loadPosts, { at: "build", staleTime: 60_000 });
---

<screen title="Posts">
  <list each={feed.data ?? []} as="post" key={post.id}>
    <text>{post.caption}</text>
  </list>
</screen>

duolith build runs loadPosts once, writes posts/index.html with the posts in it, and writes the value to _duolith/seed/posts.json. In the browser the app reads that seed before it starts, so the screen it builds shows the same posts with no request, and replaces the written one in a single step. When staleTime has passed since the build, the app runs loadPosts again in the background, as it would for any loaded state.

A loader is called as loader(key, { signal }), at build and in the app alike, so the same function serves both.

Which origins a loader may reach

At build a loader runs in its own Node process, locked down:

  • it fetches only the origins duolith.yaml lists, and every redirect is checked again (E0579);
  • it reads only the project's files, and cannot write files, start processes or open sockets (E0577);
  • it sees only DUOLITH_PUBLIC_* variables, so a secret can never reach a page's HTML (E0576);
  • it has a deadline, 10 seconds unless you say otherwise (E0578);
  • what it returns must be plain JSON (E0580).
# duolith.yaml
build:
  data:
    origins: [https://api.example.com]
    deadline: 20

An origin is a whole https site, or http on this machine (http://localhost:4480). A loader that fails, or passes its deadline, stops the build before anything is written.

Routes with parameters

A page such as pages/post/[id].duo is written once per address. List the addresses with paths() in the file beside it:

// pages/post/[id].paths.ts
export async function paths({ signal }: { signal: AbortSignal }) {
  const response = await fetch("https://api.example.com/posts", { signal });
  const posts = (await response.json()) as { id: number }[];
  return posts.map((post) => ({ id: String(post.id) }));
}
---
import { state, route } from "@duolith/client";
import { loadPost } from "../../behaviours/posts.behaviour.ts";

let { id } = route();
const post = state.load(["post", id], loadPost, { at: "build" });
---

<screen title={`${post.data?.author}'s post`}>
  <text>{post.data?.caption}</text>
</screen>

Each value is one path segment: text with no /, \, %, ?, # or control character, and not . or .. (E0582). An address no paths() entry lists is still served by the app shell, which loads the post when the screen opens.

Rebuilding only what changed

duolith build keeps a record of what it wrote in dist/.duolith/build-record.json. The next build still runs every loader, since a service's data can change with nothing in the project changing, but it writes only the files whose contents changed and removes the ones no longer built. A build with nothing changed writes nothing; one loader that returns something new rewrites only the routes that read its key. When no file of the project changed either, the type check is not run again. duolith build --force writes everything.

duolith build --report shows, for each route, its loads, when they ran, the size of its seeds, and whether it was rebuilt or kept.

On a phone

A native build runs the same loaders and puts every value they gave into the bundle, placed in the data core before the first screen. The app refreshes them by staleTime as on the web.

Deploying to Vercel

Netlify and Cloudflare Pages read the _headers file a web build writes. Vercel does not, so name it in duolith.yaml:

web:
  host: vercel

The build then also writes .vercel/output/, Vercel's Build Output API folder, with the same Content-Security-Policy, the seeds' headers, the cache headers, every route at its clean address and the not-found page. Deploy it with vercel deploy --prebuilt.

What a build-time load cannot do

  • Load private data: everything a loader returns is in the page's HTML for anyone to read. Load per-user data when the screen opens, through your own server.
  • Load from a component (E0575): load at build in the page and pass the value down.
  • Use a key the build cannot know (E0586): the key is text, or a list of literals and route parameters.