# Lith guide > 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 ```tsx 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 DE{children} } ``` - `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 ```tsx function ErrorView(status: int, message: string) { return

{status === 404 ? "Page not found" : message}

Home
} layout { return {error ? : children} } page "/orders/:id/locked" (id: int) { // a page with its own heading and sentence response.status = 409 return

Order locked

Someone else is editing order {id}.

} ``` - `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 ```tsx auth function rename(name: string(1..80)) { db.user.update({ where: { id: me.id }, data: { name } }) redirect("/", { flash: "Saved" }) } layout { return {flash &&

{flash}

}{children} } ``` - `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 ```tsx 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 ```tsx table Note own { body: string(1..500) } page "/notes" { if (!me) redirect("/login", 302) // first statement: your answer replaces the guard's 303 return

{db.note.count()} notes

} ``` - 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 api`s, `seed { }` and `migrate` blocks get no guard and no scoping. Logged-out visitors of one tenant: 7. ## 6. Tenants: own(f) ```tsx 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

{tenant?.name}

} 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) ```tsx 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
{ws.name}
} 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 ```tsx auth page "/dashboard" { return
{db.savedFilter.findMany({}).map(f =>
)}
} 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: ``, with and without JS. ## 9. File uploads ```tsx import { writeFileSync } from "node:fs" table Photo { file: string, label: string(1..80) } page "/photos" { return
} 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 ```tsx 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 ```tsx 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 ```tsx 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: "ann@acme.test", 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 ```sh 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":"ann@acme.test","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 (`
`) 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 `` value). Prefer an `api` route for anything scripted. ## 14. Run, build, start ```sh 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 ```tsx 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 ```tsx 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. - `` in an island is a live binding (pair it with `onInput`); for a field you don't control, write no `value`. A plain `` outside the island is not intercepted. - Values the browser restores (Back, reload) reach state through `onChange`/`onInput`: no `querySelector(":checked")` effect, no `autocomplete="off"`. ## 18. Carts and cookie size ```tsx table Cart { id: string } table CartLine { cart: Cart, productId: int, qty: int(1..99), unique(cart, productId) } page "/products/:id" (id: int) { let cart = /(?:^|; )cart=([\w-]{36})/.exec(request.headers.get("cookie") ?? "")?.[1] if (!cart) { cart = crypto.randomUUID() response.headers.append("Set-Cookie", `cart=${cart}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000`) } return
} function addToCart(cart: string(36..36), productId: int, qty: int(1..99)) { if (!db.cart.findUnique({ where: { id: cart } })) db.cart.create({ data: { id: cart } }) db.cartLine.create({ data: { cartId: cart, productId, qty } }) } ``` - Browsers drop a cookie over about 4 KB: keep an id in it, lines in tables. Server functions cannot read cookies (E0201): the page passes a hidden input. ## 19. Design system ```tsx page "/dashboard" { return

Sales

{tokens.color.accent}

} ``` - `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 `