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 aResponse); elsewhere E0201. Server functions cannot read the request or set cookies. Query values are page params (searchParams.getis W0644).- The runtime owns
Content-Type,Location,Content-Lengthandlith_*cookies;response.statustakes 200–203 and 400–599 (E0642). Defaults:nosniff,X-Frame-Options: SAMEORIGIN,frame-ancestors 'self'; pages readingmegetCache-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 }ornull) exists only in the layout; replacechildrenwith it.- Error pages: 404 (
notFound(), anOrThrow/ownmiss, unknown path), 403 (forbidden(),auth(pred), a refused cross-site request: printerror.message),failin 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 setsresponse.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 | nullexists 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 withX-Lith-Login: 1.- A typed param that fails answers 400
{"error","field"}. For a ticket's own body or status, type the paramunknown(apis only, E0601) and narrow it (E0300). A non-JSON body is 400invalid JSON body. I0914 marks hand-parsedrequest.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
ownorown(f)table, directly or through functions it calls, requires a login and hasme: User: a page redirects to/login(303), an api, crud or RPC answers 401. - A page, api or server function whose first statement handles
!meand stops (redirect,return,fail,unauthorized) keeps its own answer. Scoping still applies.auth pagestays 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 }). Writeauth functionwhere a function needs a login. dev apis,seed { }andmigrateblocks 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;organisationindatais E0300 outside fixture code. No tenant: reads find nothing, writes are forbidden. tenantis the request's tenant row (me.organisation, or the bound one: 7),nullwithout one.Userand the tenant table stay unscoped: filter them withtenant.idafterif (!tenant) notFound(). Neverme?.organisationIdin awhere(E0521:undefineddrops the filter, so every tenant's rows match).- A per-user table inside a tenant is
own. Hand-writtenorganisationId: me.organisationIdclauses (I0950):lith fix, thenlith 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 noworkspaceIdfilters or helper parameters. - No login there:
meisnull(E0520 forme,owntables,login), the session cookie is untouched,systemis 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: stringkeeps 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; anapiwhen a ticket names the URL or a script posts there too. Fields fill params as for functions; path params come only from the path. Withoutredirect, 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
Fileparam (File | null,File[]formultiple; astringparam is E0608). The form is multipart by itself and works without JS. Anapi POSTtakesFileparams too. Base64 viaFileReader: I0916. File(..n)limits each file ("Too large") and raises that route's body limit.file.name/file.typecome 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 (seedwrites the new shape). - Unscoped: give
owner/fyourself (E0522), one tenant per row. Noawait,fetch,me(E0518). Removed union values type-check only here. A top-leveldbcall 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 --statuslists 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 becomeinviteId: string; default order is insertion order. - E0508 bad
idtype; E0509User's id staysint; E0515idin create data of anown/own(f)table outside fixture code, or in anyupdate. Existing tables keep their key (E0505) andrefcolumns (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 devandlith start --dev-api. No scoping or cross-site check, neverauth(E0101); links to it are W0646; env-gated hook apis: F0303.asUserexists only intestblocks (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_ORIGINexactly. Playwright'srequestcontext with cookies needsheaders: { 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 anapiroute 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 startrefuses to run withoutLITH_ORIGIN; anotherHostgets 421; behind a proxy:LITH_TRUST_PROXY=1. It printslisteningonce the port is bound; a taken port exits with "port … is in use".LITH_SECRETsigns sessions (unset:.lith/secret);LITH_DB;PORT.lith.json:"src","bodyLimit". Commitlith.tokens.lock.- Output is
.lith/build/.testblocks are type-checked; there is nolith testrunner 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()andformData()each work once. Check the provider's timestamp too. No cookies: no CSRF check. Tables it writes can beown(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
Responsepasses through. Stop = abort the browser'sfetch(state ctrl: AbortController | null), which runscancel(). Island:res.body!.pipeThrough(new TextDecoderStream()).getReader(). Stream callbacks keep the request'smeor 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
constin a component recomputes when the state or props it reads change; a handler reads current values. effectruns 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 withonInput); for a field you don't control, write novalue. A plain<form method="get">outside the island is not intercepted.- Values the browser restores (Back, reload) reach state through
onChange/onInput: noquerySelector(":checked")effect, noautocomplete="off".
18. Carts and cookie size
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 <main><form action={addToCart}><input type="hidden" name="cart" value={cart} /> <input type="hidden" name="productId" value={id} /><input name="qty" value="1" /><button>Add</button></form></main> } 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
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 --summaryprints the names. Default: colourssurface raised text muted border accent on-accent danger success warning highlight, spacinginset stack section, radiuscontrol card, sizessmall body heading title. Role classesgap-space p-space bg-raised text-dangerwork 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:flexreplaces amatchMediaisland (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;migratechanges 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 giveowner,fandid.aggregate/groupByare scoped likefindMany, never readpasswordHash;_countinincludeis 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 withIntl.<input type="datetime-local">fills aDateparam 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 isLITH_ORIGIN. A sitemap is anapi GET "/sitemap.xml"returning anapplication/xmlResponse.
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). Plainowner: Usertables (seeds could not setowner) can beown(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:unknownparams (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 newwritesAGENTS.md(andCLAUDE.md).lith docs <words>prints about 1.5k tokens of the best passages (lith docs bindTenant,lith docs upload);--listlists topics.lith mcp(stdio) orhttps://lith.codes/mcpservelith_docs,lith_check,lith_fix,lith_tokens:claude mcp add lith -- node <compiler>/bin/lith.mjs mcp.