Guide · v0.4

Recipes for the rest.

24 tasks the card leaves out, from cookies and error pages to webhooks, streaming and the design system. Every example passes lith check.

For agents

The same recipes as plain text: /llms-guide.txt, 7,079 tokens. Read the card first, or look up a single recipe with lith docs or the MCP server.

Recipes for Lith v0.4 tasks the card (llms.txt) does not cover; read the card first. Code, then rules and codes. Exact rules: llms-full.txt (its first line lists sections and sizes).

1. Request, headers, cookies

function cookie(header: string | null, name: string) {
  const m = new RegExp(`(?:^|; )${name}=([^;]*)`).exec(header ?? "")
  return m ? decodeURIComponent(m[1]) : null
}
page "/lang/:l" (l: "en" | "de") {                  // a preference cookie is set by a GET page
  response.headers.append("Set-Cookie", `lang=${l}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000`)
  redirect("/")
}
layout {
  const lang = cookie(request.headers.get("cookie"), "lang") ?? "en"
  const url = new URL(request.url)                   // url.search, url.origin, url.searchParams.has("x")
  response.headers.set("X-Frame-Options", "DENY")    // a default: a header the page set wins
  return <html lang={lang}><a href={`/lang/de${url.search}`}>DE</a>{children}</html>
}
  • request: pages, layout, apis; response: pages, layout (an api returns a Response); elsewhere E0201. Server functions cannot read the request or set cookies. Query values are page params (searchParams.get is W0644).
  • The runtime owns Content-Type, Location, Content-Length and lith_* cookies; response.status takes 200–203 and 400–599 (E0642). Defaults: nosniff, X-Frame-Options: SAMEORIGIN, frame-ancestors 'self'; pages reading me get Cache-Control: private. Embeddable page (iframe, widget): section 7.

2. Error pages

function ErrorView(status: int, message: string) {
  return <main><h1>{status === 404 ? "Page not found" : message}</h1><a href="/">Home</a></main>
}
layout {
  return <html><nav><a href="/">Home</a></nav>{error ? <ErrorView status={error.status} message={error.message} /> : children}</html>
}
page "/orders/:id/locked" (id: int) {               // a page with its own heading and sentence
  response.status = 409
  return <main><h1>Order locked</h1><p>Someone else is editing order {id}.</p></main>
}
  • error ({ status, message, fields } or null) exists only in the layout; replace children with it.
  • Error pages: 404 (notFound(), an OrThrow/own miss, unknown path), 403 (forbidden(), auth(pred), a refused cross-site request: print error.message), fail in a GET page (its message is the heading), 409, 500. From a form, notFound()/forbidden() show the error page. A page with its own heading and text sets response.status.

3. Flash

auth function rename(name: string(1..80)) {
  db.user.update({ where: { id: me.id }, data: { name } })
  redirect("/", { flash: "Saved" })
}
layout { return <html>{flash && <p role="status">{flash}</p>}{children}</html> }
  • flash: string | null exists in pages, the layout and server components; an island gets it as a prop (E0401).
  • Read by the next 2xx/4xx HTML page, so it survives redirect chains and logout/login; a re-shown form keeps it for later. Max 1 kB, 60 s. It is a message: data the next page needs goes in the path.

4. Login, 401 and your own validation answer

api POST "/api/login" (email: string, password: string) {   // for scripts and clients
  const u = loginWithPassword(email, password)
  if (!u) fail("Invalid email or password.", 401)
  return { id: u.id, name: u.name }
}
table User { widgetEnabled: boolean = false }
api PUT "/api/settings" (widgetEnabled: unknown) {          // unknown: read, not validated
  if (!me) return Response.json({ error: "unauthenticated" }, { status: 401 })
  if (typeof widgetEnabled !== "boolean") return Response.json({ error: "validation_failed", fields: { widgetEnabled: "Choose" } }, { status: 422 })
  return db.user.update({ where: { id: me.id }, data: { widgetEnabled } })
}
  • fail(msg, 401) (in a form login too) re-shows or answers 401; statuses 400 401 402 403 404 409 410 412 413 415 422 423 429 (E0613). unauthorized() = "log in first": 303 to /login, or 401 with X-Lith-Login: 1.
  • A typed param that fails answers 400 {"error","field"}. For a ticket's own body or status, type the param unknown (apis only, E0601) and narrow it (E0300). A non-JSON body is 400 invalid JSON body. I0914 marks hand-parsed request.json(). A login posted from another site is 403 even without cookies.

5. Implicit guards

table Note own { body: string(1..500) }
page "/notes" {
  if (!me) redirect("/login", 302)                 // first statement: your answer replaces the guard's 303
  return <main><p>{db.note.count()} notes</p></main>
}
  • Code that queries an own or own(f) table, directly or through functions it calls, requires a login and has me: User: a page redirects to /login (303), an api, crud or RPC answers 401.
  • A page, api or server function whose first statement handles !me and stops (redirect, return, fail, unauthorized) keeps its own answer. Scoping still applies. auth page stays 303.
  • Rows of other owners act as missing: 404, never 403. Arguments come from the browser: check ownership of rows in plain tables (where: { id, authorId: me.id }). Write auth function where a function needs a login.
  • dev apis, seed { } and migrate blocks get no guard and no scoping. Logged-out visitors of one tenant: 7.

6. Tenants: own(f)

table Organisation { name: string(1..80) }
table User { organisation: Organisation | null, role: "Owner" | "Member" = "Member" }
table Project own(organisation) { name: string(1..80) unique }      // unique per organisation
auth page "/projects" {
  const projects = db.project.findMany({ orderBy: { name: "asc" } })   // only my organisation's rows
  return <main><h1>{tenant?.name}</h1><ul>{projects.map(p => <li>{p.name}</li>)}</ul>
    <form action={addProject}><input name="name" /><button>Add</button></form></main>
}
auth function addProject(name: string) { db.project.create({ data: { name } }) }   // organisationId is filled
  • Reads, updates, deletes and aggregates match organisationId = me.organisationId; create fills it; uniques are per tenant; organisation in data is E0300 outside fixture code. No tenant: reads find nothing, writes are forbidden.
  • tenant is the request's tenant row (me.organisation, or the bound one: 7), null without one. User and the tenant table stay unscoped: filter them with tenant.id after if (!tenant) notFound(). Never me?.organisationId in a where (E0521: undefined drops the filter, so every tenant's rows match).
  • A per-user table inside a tenant is own. Hand-written organisationId: me.organisationId clauses (I0950): lith fix, then lith fix --own Project.

7. Visitor routes: bindTenant (public pages, widgets, embeds)

table Workspace { slug: string(1..60) unique, name: string, widgetEnabled: boolean = false }
table User { workspace: Workspace | null }
table Faq own(workspace) { question: string, answer: string }
table Conversation own(workspace) { id: string, user: User | null }
table Message own(workspace) { conversation: Conversation, body: string(1..4000) }
page "/embed/:slug" (slug: string) {                 // an embeddable page (iframe)
  const ws = db.workspace.findUnique({ where: { slug } })
  if (!ws || !ws.widgetEnabled) notFound()
  bindTenant(ws)                                     // own(workspace) tables now mean ws's rows
  response.headers.delete("X-Frame-Options")
  response.headers.set("Content-Security-Policy", "frame-ancestors *")
  return <main><title>{ws.name}</title><ul>{db.faq.findMany({}).map(f => <li>{f.question}</li>)}</ul></main>
}
api POST "/api/public/:slug/chat" (slug: string, conversationId: string | null = null, message: string(1..4000)) {
  const ws = db.workspace.findUnique({ where: { slug } })
  if (!ws || !ws.widgetEnabled) return Response.json({ error: "not_found" }, { status: 404 })
  bindTenant(ws)
  const old = conversationId === null ? null : db.conversation.findFirst({ where: { id: conversationId, userId: null } })
  const convo = old ?? db.conversation.create({ data: {} })     // workspace is filled from the binding
  db.message.create({ data: { conversationId: convo.id, body: message } })
  return { conversationId: convo.id }
}
  • Look the tenant up (tenant table or an unscoped key table), stop on a miss, then bindTenant(row) once, top-level, before the first query (E0519). The route then needs no workspaceId filters or helper parameters.
  • No login there: me is null (E0520 for me, own tables, login), the session cookie is untouched, system is E0510. The layout and error pages see no tenant. A server function on a visitor page binds itself.
  • Helpers shared with member pages return member-grade rows (W0648): filter for visitors (userId: null). id: string keeps visitor rows unguessable (I0952). Add a per-tenant rate limit.
  • API keys and webhooks: compare the key (timingSafeEqual) or verify the signature, then bind. Subdomains cannot pick a tenant (421). frame-ancestors * is safe here (no session); listing the tenant's origins is tighter.

8. Forms that post to a named route

auth page "/dashboard" {
  return <main>
    <form method="post" action="/dashboard/filters"><label for="n">Filter name</label><input id="n" name="name" /><button>Save filter</button></form>
    {db.savedFilter.findMany({}).map(f => <form method="post" action={`/dashboard/filters/${f.id}/delete`}><button>Delete {f.name}</button></form>)}
  </main>
}
table SavedFilter own { id: string, name: string(1..60) }
auth api POST "/dashboard/filters" (name: string) {
  if (name.trim() === "") fail({ name: "Give the filter a name" }, 422)   // re-shows /dashboard, message after the input
  db.savedFilter.create({ data: { name } })
  redirect("/dashboard", { flash: "Filter saved." })
}
auth api POST "/dashboard/filters/:id/delete" (id: string) {
  db.savedFilter.delete({ where: { id } })        // another user's filter is missing: 404
  redirect("/dashboard", { flash: "Filter deleted." })
}
  • action={fn} by default; an api when a ticket names the URL or a script posts there too. Fields fill params as for functions; path params come only from the path. Without redirect, success returns to the page.
  • method="post" is required (E0609); routes and input names are checked (E0602, E0607); crud takes JSON only.
  • Two actions in one form: <button formaction={/approvals/${a.id}/reject}>Reject</button>, with and without JS.

9. File uploads

import { writeFileSync } from "node:fs"
table Photo { file: string, label: string(1..80) }
page "/photos" {
  return <main><form action={addPhoto}><input name="label" /><input type="file" name="photo" accept="image/png,image/jpeg" /><button>Upload</button></form></main>
}
auth function addPhoto(label: string(1..80), photo: File(..5000000) | null) {
  if (photo === null) fail({ photo: "Choose a file" })
  const bytes = Buffer.from(await photo.arrayBuffer())
  const ext = bytes[0] === 0x89 ? "png" : bytes[0] === 0xff ? "jpg" : null   // sniff the bytes, not photo.type
  if (ext === null) fail({ photo: "Only PNG or JPEG files" })
  const name = `${crypto.randomUUID()}.${ext}`
  writeFileSync(`uploads/${name}`, bytes)
  db.photo.create({ data: { file: name, label } })
}
  • A file input fills a File param (File | null, File[] for multiple; a string param is E0608). The form is multipart by itself and works without JS. An api POST takes File params too. Base64 via FileReader: I0916.
  • File(..n) limits each file ("Too large") and raises that route's body limit. file.name/file.type come from the browser (W0649): name files yourself. Not a column type.

10. Data migrations

migrate "2026-10-18-project-roles" {
  for (const org of db.organisation.findMany({})) {
    if (db.projectMember.count({ where: { organisationId: org.id } }) > 0) continue   // already upgraded
    const users = db.user.findMany({ where: { organisationId: org.id, role: { not: "Owner" } } })
    for (const p of db.project.findMany({ where: { organisationId: org.id } })) for (const u of users)
      db.projectMember.create({ data: { organisationId: org.id, projectId: p.id, userId: u.id, role: u.role === "Admin" ? "Manager" : "Contributor" } })
  }
  db.user.updateMany({ where: { role: "Admin" }, data: { role: "Member" } })   // "Admin" was removed from the union
}
  • Runs once per database at start, before requests, in name order (YYYY-MM-DD-name, E0518), one transaction each; an error stops the start. A fresh database records blocks without running them (seed writes the new shape).
  • Unscoped: give owner/f yourself (E0522), one tenant per row. No await, fetch, me (E0518). Removed union values type-check only here. A top-level db call is E0517.
  • Replacing a lazy upgrade: test the same "not yet upgraded" condition. Drop columns a block reads in a later release. Editing an applied block is W0507 (lith migrate --redo "name" on dev). lith migrate --status lists blocks.

11. String ids

table Invite { id: string, email: email, accepted: boolean = false }
function sendInvite(email: email) {
  const inv = db.invite.create({ data: { email } })   // id = crypto.randomUUID()
  redirect(`/invite/${inv.id}`)
}
  • 1–64 characters of A–Z a–z 0–9 _ -; references become inviteId: string; default order is insertion order.
  • E0508 bad id type; E0509 User's id stays int; E0515 id in create data of an own/own(f) table outside fixture code, or in any update. Existing tables keep their key (E0505) and ref columns (I0951).

12. Test hooks: dev api

table Team { name: string(1..80) }
table User { team: Team | null }
table Task own(team) { title: string(1..200) }
table Draft own { text: string }
dev api POST "/__test/reset" {
  db.task.deleteMany({}); db.draft.deleteMany({}); db.user.deleteMany({}); db.team.deleteMany({})
  const team = db.team.create({ data: { name: "Acme" } })
  const ann = db.user.create({ data: { email: "[email protected]", name: "Ann", passwordHash: hashPassword("test-pw-1"), team } })
  db.task.create({ data: { title: "First", team } })       // f, owner and id are given here
  db.draft.create({ data: { text: "Hi", owner: ann } })
  return new Response(null, { status: 204 })
}
  • Mounted only by lith dev and lith start --dev-api. No scoping or cross-site check, never auth (E0101); links to it are W0646; env-gated hook apis: F0303. asUser exists only in test blocks (E0516).

13. Scripts, curl and CSRF

B=http://localhost:3901; O="Origin: $B"
curl -s -X POST $B/__test/reset                                         # dev api: no check
curl -s -c jar -H "$O" -H 'Content-Type: application/json' -d '{"email":"[email protected]","password":"test-pw-1"}' $B/api/login
curl -s -b jar -H "$O" -d 'name=Weekly' $B/dashboard/filters           # an api form route, urlencoded
  • A non-GET request with any cookie needs a same-origin Origin, else 403 {"error":"cross-site request","help":…}. Same origin = LITH_ORIGIN exactly. Playwright's request context with cookies needs headers: { Origin }.
  • Script against apis (JSON or form bodies), not /_lith/rpc. Cookie-less requests are not checked (logged out).
  • A script that submits a server-function form (<form action={fn}>) posts to the page's own path with the form's fields plus the hidden __lith_fn (function name) and __lith_csrf (the page's <meta name="lith-csrf"> value). Prefer an api route for anything scripted.

14. Run, build, start

lith dev [dir] --port 3000      # watch, rebuild, migrate; dev apis mounted; origin = the request's own
lith check [dir] [--all]        # hints (I…, F…) never fail it
lith build [dir] && LITH_ORIGIN=http://localhost:3000 lith start [dir] --port 3000 [--dev-api]
  • lith start refuses to run without LITH_ORIGIN; another Host gets 421; behind a proxy: LITH_TRUST_PROXY=1. It prints listening once the port is bound; a taken port exits with "port … is in use".
  • LITH_SECRET signs sessions (unset: .lith/secret); LITH_DB; PORT. lith.json: "src", "bodyLimit". Commit lith.tokens.lock.
  • Output is .lith/build/. test blocks are type-checked; there is no lith test runner yet.

15. Webhooks

import { createHmac, timingSafeEqual } from "node:crypto"
table Organisation { name: string, payAccount: string unique }
table Payment own(organisation) { orderRef: string(1..64) unique, status: "paid" | "failed" }
api POST "/api/webhooks/pay" {
  const raw = Buffer.from(await request.arrayBuffer())
  const sig = Buffer.from(request.headers.get("x-pay-signature") ?? "", "hex")
  const want = createHmac("sha256", process.env.PAY_SECRET ?? "").update(raw).digest()
  if (sig.length !== want.length || !timingSafeEqual(sig, want)) return Response.json({ error: "bad signature" }, { status: 401 })
  const ev = JSON.parse(raw.toString("utf8"))
  const org = db.organisation.findUnique({ where: { payAccount: String(ev.account) } })
  if (!org) return Response.json({ error: "unknown account" }, { status: 404 })
  bindTenant(org)                                     // signature first, then the tenant
  const orderRef = String(ev.orderRef)
  if (!db.payment.findUnique({ where: { orderRef } })) db.payment.create({ data: { orderRef, status: "paid" } })
  return { ok: true }
}
  • The body is buffered: arrayBuffer(), text(), json() and formData() each work once. Check the provider's timestamp too. No cookies: no CSRF check. Tables it writes can be own(f) once it binds the tenant.

16. Streaming

table Reply { body: string = "", status: "streaming" | "done" | "stopped" = "streaming" }
api POST "/api/chat" (prompt: string(1..4000)) {
  const reply = db.reply.create({ data: {} })
  let text = ""
  const body = new ReadableStream({
    async start(controller) {
      for (const word of prompt.split(" ")) {     // stand-in for the model's chunks
        text += word + " "
        controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ text: word + " " })}\n\n`))
      }
      db.reply.update({ where: { id: reply.id }, data: { body: text, status: "done" } })
      controller.close()
    },
    cancel() { db.reply.update({ where: { id: reply.id }, data: { body: text, status: "stopped" } }) }   // client aborted
  })
  return new Response(body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
}
  • Pages are never streamed; an api's streaming Response passes through. Stop = abort the browser's fetch (state ctrl: AbortController | null), which runs cancel(). Island: res.body!.pipeThrough(new TextDecoderStream()).getReader(). Stream callbacks keep the request's me or bound tenant.

17. Islands: what runs where

  • A top-level function without server effects is pure: it runs on the server and in islands, so an island may call it.
  • A const in a component recomputes when the state or props it reads change; a handler reads current values.
  • effect runs after mount and after changes to what it read synchronously; reads inside timers and promises are not dependencies. An effect's own writes do not re-run it.
  • <input value={x}> in an island is a live binding (pair it with onInput); for a field you don't control, write no value. A plain <form method="get"> outside the island is not intercepted.
  • Values the browser restores (Back, reload) reach state through onChange/onInput: no querySelector(":checked") effect, no autocomplete="off".

19. Design system

page "/dashboard" {
  return <main class="grid grid-cols-1 md:grid-cols-3 gap-space">
    <style>{`@media (max-width: var(--md)) { .wide-only { display: none } }`}</style>
    <section class="bg-raised p-space rounded-card"><h2 class="text-heading">Sales</h2><p class="text-muted">{tokens.color.accent}</p></section>
  </main>
}
  • lith tokens --summary prints the names. Default: colours surface raised text muted border accent on-accent danger success warning highlight, spacing inset stack section, radius control card, sizes small body heading title. Role classes gap-space p-space bg-raised text-danger work with every token file. A filled badge: bg-accent text-on-accent.
  • Breakpoints sm md lg xl 2xl (or the token file's breakpoint group); in <style>, @media (min-width: var(--md)) (raw px: E0620). hidden md:flex replaces a matchMedia island (I0907).
  • E0620 raw value, E0621 primitive, E0622 unknown token, each with a patch. Dark mode: data-theme="system", dark:.

20. Seed data and reports

import data from "./seed-data.json"
table Item { slug: string(1..80) unique, name: string, kind: "Wreath" | "Bouquet", priceCents: int }
function loadSeed() {
  for (const i of data.items) db.item.create({ data: { slug: i.slug, name: i.name, kind: i.kind === "Wreath" ? "Wreath" : "Bouquet", priceCents: i.price } })
}
seed { loadSeed() }
api GET "/api/report" {
  const total = db.item.aggregate({ _sum: { priceCents: true }, _count: true })   // { _sum: { priceCents }, _count }
  const byKind = db.item.groupBy({ by: ["kind"], _count: true, orderBy: { kind: "asc" } })
  return { total: total._sum.priceCents ?? 0, items: total._count, byKind }
}
  • seed { } fills an empty database, unscoped; migrate changes existing data (10). A JSON import is typed from the file (I0911): map its strings to a literal union. Code reached only from seeds may give owner, f and id.
  • aggregate/groupBy are scoped like findMany, never read passwordHash; _count in include is E0502.

21. Days and time zones

function localDay(tz: string): day { return new Intl.DateTimeFormat("en-CA", { timeZone: tz }).format(new Date()) }
  • today(), now() and {date} in JSX are UTC. Store a user's zone and format with Intl. <input type="datetime-local"> fills a Date param with the browser's offset.

22. SEO

page "/p/:slug" (slug: string) {
  const p = db.page.findUniqueOrThrow({ where: { slug } })
  return <main><title>{p.title}</title><meta name="description" content={p.summary} />
    <link rel="canonical" href={`${new URL(request.url).origin}/p/${p.slug}`} /><h1>{p.title}</h1></main>
}
  • <title>, <meta> (also <meta name="robots" content="noindex">) and <link> anywhere, even in a fragment or beside an island, move into <head>. The origin is LITH_ORIGIN. A sitemap is an api GET "/sitemap.xml" returning an application/xml Response.

23. Upgrading from v0.3.1

lith fix --list shows the project's hints; lith fix applies the safe rewrites and re-checks.

  • Tables kept hand-scoped for visitors or webhooks can be own(f): bind the tenant (7; lith fix --own T, F0304). Plain owner: User tables (seeds could not set owner) can be own (12).
  • Server-function forms on the page's URL where a ticket names a route: an api form (8). Lazy per-request upgrades: migrate (10). Base64 uploads: File (9, I0916). request.json() validators: unknown params (4, I0914).
  • Behaviour: form posts to apis now fill params; if (!me) redirect(…) keeps its status in pages.

24. Agents: AGENTS.md, lith docs, MCP

  • lith new writes AGENTS.md (and CLAUDE.md). lith docs <words> prints about 1.5k tokens of the best passages (lith docs bindTenant, lith docs upload); --list lists topics. lith mcp (stdio) or https://lith.codes/mcp serve lith_docs, lith_check, lith_fix, lith_tokens: claude mcp add lith -- node <compiler>/bin/lith.mjs mcp.