Build an app, step by step
This walks through building a whole app with Surfaces UI, from an empty folder to an app that is checked, tested in a browser and running on your own backend. It is written for people and for agents. Each step says what to do, then names the recipe that shows it done in tested code. A person can follow it top to bottom. An agent can be given this page and a brief (there is one to copy at the end).
Four recipes are the worked examples. Each is source, a test, a page you can open, a browser test that walks it on every change, and the screenshots that test took:
| Recipe | What it shows | Drawn with |
|---|---|---|
| A storefront | Home, a sale with filters, a product, a cart with a promo code, checkout with test cards, the confirmation | This library's components, plus one of the shop's own (extendCatalog) |
| Compute setup | Setting up a database's compute, approved before it costs money; changing its settings; suspending and deleting it | This library's components |
| An app drawn with MUI | A support desk written by a live model, drawn with MUI's components and dialog | Your own components (MUI) |
| An app drawn with web components | The same desk with plain custom elements, and the whole app as one <desk-app> element | Your own web components |
The storefront's cart, drawn with this library's components
What an app is made of
An app has four parts. Only the last is specific to one app.
- A backend. It has two parts. A
DataSourceanswers queries, and it sorts, filters and pages in SQL, never in the browser.Operationsare the changes your server defines: an id, its arguments, its rules and whether a person must approve. The page sends an id and arguments, never SQL or a table name. In production these are your own services: no Surfaces UI server is needed (adapters). - A catalog. It lists the components a document may use and the props each takes. It is what an agent is told and what every document is checked against. Use this library's (
analyticsCatalog,appCatalog), extend it with a few of your own (extendCatalog), or write one for your own component library (defineCatalog). - Renderers. They draw each catalog component. This library's come with its catalogs (
analyticsRenderersfrom@surfaces-ui/spec/react). For your own components you write one function per component. - The app document. This is JSON with no code: routes and their pages, the navigation, the values pages share, the records a page reads, and the operations its buttons run. A person or an agent writes it, it is checked before it runs, and it is stored and reviewed like any file.
The shell that joins them is a few lines: AppView with the document, the catalog, the renderers, the backend and the address.
Before you start
You need Node 22 or later and pnpm (corepack enable).
To run the recipes first, from a clone of this repository:
pnpm install
pnpm build
pnpm --filter @surfaces-ui/recipes exec vite src/storefront # or compute-setup, mui-components, web-componentsOpen the address Vite prints. Add ?mode=dark for dark. Each recipe's backend runs in memory in the page, so nothing else needs to be running.
To start an app of your own in another project:
npx create-surfaces my-app # a dashboard, a chat and a data server with six sample datasetsOr install only what your path needs:
# With this library's components
npm install @surfaces-ui/spec @surfaces-ui/components @surfaces-ui/data
# With your own components (MUI, web components, anything): no component of ours
npm install @surfaces-ui/document @surfaces-ui/runtime @surfaces-ui/dataGetting started covers the providers, data sources and theming in more depth.
Step 1: the backend
Start with what the app reads and what it may change, before any page.
- Reads. These are the tables or queries the pages show. While you build,
memoryDataSource({ tables })serves rows from memory and honours sorts, filters and paging. In production, implementDataSourceover your own API (own-datasource, rest-datasource), or use an engine adapter for DuckDB, Teradata, Postgres and the rest (connect-sources). - Changes. Each change is an operation:
memoryOperations({ operations: [...] })while you build, and your own handler in production (own-operations). For each operation, decide: - its arguments, with labels, help, choices, limits and patterns. A form draws its fields from these, so write them for the person filling it in.
- its rules, which stay on the server. Throw
OperationErrorwith words a person can act on, for example "Only 3 left of the Alpine hiking boot." or "That needs up to 32 credits an hour, and running compute already uses up to 20 of the account's 48." - its
risk.highasks a person first.irreversiblealso asks for the word "confirm", andreasonRequiredasks why. - a
versionargument andStaleOperationErrorwhere two people could change the same record, so a save over someone else's change is refused rather than lost. refreshes, the sources it changes, so the pages read them again.
Worked examples: the shop's stock, promo codes, totals and test cards in shop.ts, and compute's credit limit, approvals and "suspend before delete" in compute.ts.
Fake data and payments. Make up every name, price and person. A checkout takes only test card numbers, keeps only the last four digits and says on the page that it is in test mode. The storefront shows all three.
Step 2: the catalog
- This library's components:
analyticsCatalog(data, charts, forms and records) orappCatalog(records and forms, with a much smaller agent prompt). Nothing to write. - One or two of your own beside them:
extendCatalog(analyticsCatalog, { id, components: { SaleHero: {...} } }), with a renderer for each new one (storefront). Its CSS uses the theme's--sf-*variables, so it follows light, dark and every preset. - Your own component library:
defineCatalog, one entry per component, with a description an agent reads, Zod props and a valid example (mui-components). Web components are drawn from the same kind of catalog (web-components).
Step 3: the app document
Write the document. Build it one route at a time:
- Routes and navigation. Start with
/and addnavitems.[id]in a route takes a value from the address, read at/@route/id. - Lists that open a record. A
DataGridwithrowKeyand anactionthat navigates to/things/[id], or aRowListwhose child template reads each row's columns (compute, storefront). - One record. Give the page a
record(sourceId,sql,key) and read it at/@record/page/<column>. - Changes. A
Buttonwhose action isrunwith an operation id and arguments, andthento go on afterwards.thencan read what the operation returned, at/@run/<buttonId>/result/.... ARecordFormsaves a record, withversionso stale saves are refused. With no record it is a form for a new one, and its fields are the operation's own arguments. The page'sdata.draft.<formId>fills it in first. - Shared values. Declare them in
stateand read them at/app/<name>.keep: "url"puts one in the address, andkeep: "session"keeps it for the tab. - Only what a person chose.
requiresmakes a button wait for the fields it needs, andvisibleWhenshows a control only when it applies, such as Suspend for a running compute.
Apps as documents is the reference for each of these.
Step 4: check it before it runs
const { operations } = await backend.listOperations({});
validateApp(app, catalog, appOperationChecks(operations)); // routes, state, every component, every run and its arguments
await validateAppData(app, catalog, dataSource); // every source, every query, every column a component namesBoth return problems with where they are, and an empty list means none. Run them in the shell (refuse to draw an app with problems) and in its test. Give validateAppData a source with rows in every table, so every column is checked. The storefront's test places an order first.
Step 5: the shell
<ThemeProvider initialMode="light" storage={null}>
<DataSourceProvider dataSource={dataSource}>
<AppView app={app} catalog={catalog} renderers={renderers} operations={operations} operationDefinitions={operations} {...useHashLocation()} />
</DataSourceProvider>
</ThemeProvider>With your own components, AppView from @surfaces-ui/runtime takes your pieces in its slots:
nav: your navigation.confirm: your approval dialog (MUI'sDialog, or<desk-confirm>).themeScope: a document's theme request mapped onto your theme.resolveImage: a picture's name turned into an address, such as your CDN's. AnImagenever loads an address a document wrote.
Three hooks let your renderers show what the server said:
useRunState(id)in a button: busy, refused or stale.useRunFieldError(path)in an input: the server's words at the field it named, with focus moved there.useAppLinks()in a link.
Step 6: test it, in jsdom and in a browser
Every recipe has both kinds of test. Copy them.
- A unit test (Vitest with jsdom, next to the code):
- check the document with
validateAppandvalidateAppData. - hold the backend to each of its rules, with every total worked out by hand.
- walk one path through the page with Testing Library.
- A browser test (Playwright, in
apps/e2e/tests) walks the happy path and what goes wrong on the way, at desktop width in light and dark and at phone width. At each state that matters it runs axe's WCAG 2.2 AA checks and checks for no sideways scroll; it also checks for no console errors.openRecipeandlookinapps/e2e/tests/recipes.tsdo this for a recipe's page. Run them withpnpm e2e storefront. - Screenshots come from that browser test:
SURFACES_EVIDENCE_DIR=/some/folder pnpm e2e storefrontsaves eachlookas a PNG. Commit a few per recipe in itsscreenshots/folder, at 960 pixels wide and 64 colours (convert in.png -resize 960x -dither None -colors 64 PNG8:out.png), and show them in itsrecipe.md.
Step 7: on your own backend
Swap the in-memory parts for your own:
- a
DataSourceover your API or database. httpOperationsagainst your route, whose handler iscreateOperationHandler(@surfaces-ui/data/server) and your rules (own-operations).
Prove each with the conformance suite (@surfaces-ui/data/conformance, adapters). The document, the catalog and the renderers do not change.
For agents
An agent that writes the app document
The document is the part an agent writes. Give the model the catalog's prompt and the backend's operations, and check what it sends before anything runs:
import { appAgentPrompt, parseApp, validateApp, validateAppData } from "@surfaces-ui/document";
import { appTool } from "@surfaces-ui/agent";
import { appOperationChecks } from "@surfaces-ui/spec";
const { operations } = await backend.listOperations({});
const system = appAgentPrompt(catalog, { operations }); // the components, the rules and each operation with its arguments
const writeApp = appTool({
check: async (input) => {
const parsed = parseApp(input);
if ("problems" in parsed) return parsed.problems;
const problems = validateApp(parsed.app, catalog, appOperationChecks(operations));
return problems.length ? problems : (await validateAppData(parsed.app, catalog, dataSource)).problems;
},
onApp: (app) => save(app),
});Every problem goes back to the model as the tool's error, to fix in the same turn, and only an app with none is kept. The agent cannot add an operation, change one or press a button: a run happens only when a person presses something, and the backend asks that person to approve where the operation needs it. The MUI recipe's app was written this way by a live model. The generate-app recipe shows the loop, and the eval measures it.
A coding agent building an app like these
A coding agent (Claude Code, or another) working in this repository follows AGENTS.md:
- read the notes beside a folder before changing it.
- run
pnpm check:notes,pnpm typecheckand the tests. - run
pnpm docs:genafter changing a recipe.
A recipe is done when:
- its folder under
apps/recipes/src/<name>has the source,recipe.mdand a passing test. - it has a page (
index.html,main.tsx,vite.config.ts). - it has a browser test in
apps/e2e/tests/<name>.spec.ts, passing at desktop light, desktop dark and phone width with no axe violation and no console error. - its screenshots, taken by that test, are committed and shown in
recipe.md. pnpm docs:genhas written its page indocs/recipes.
In another project, the surfaces-analytics plugin gives Claude Code the skills and the MCP server (surfaces-analytics).
A brief to give an agent
Copy this, fill in the parts in angle brackets, and give it to a coding agent with this page:
Build <what the app is for> as a Surfaces UI app, following docs/build-an-app.md. - Pages: <the routes, from home to the last step, and what each shows>. - Changes: <each thing a person can change; which need approval; what cannot be undone>. - Rules the backend keeps: <limits, checks, what is refused and in what words>. - Data: made up, in memory (memoryDataSource,memoryOperations). Payments only with test cards, keeping the last four digits. - Components: <this library's | ours: (library) | web components>. Done means: -validateAppandvalidateAppDatareport nothing. - Every backend rule is tested. - A Playwright test walks the happy path and each refusal at desktop light, desktop dark and phone width, with no axe WCAG 2.2 AA violation and no console error. - Screenshots from that test are committed with the recipe. -pnpm docs:gen,pnpm check:notesandpnpm typecheckpass.
The storefront and compute recipes were built from a brief of two sentences, and held to the list under "Done means".
Checklist
- [ ] The backend's reads and operations, with every rule on the server and its refusal in words a person can act on.
- [ ] Approval on anything that costs money or cannot be undone;
versionwhere two people could collide. - [ ] A catalog: this library's, extended, or your own.
- [ ] The app document, checked by
validateApp(with the operations) andvalidateAppData. - [ ] A shell that refuses to draw an app with problems.
- [ ] Unit tests of the document, the rules and one path through the page.
- [ ] A browser test at desktop light, desktop dark and phone width: axe clean, no sideways scroll, no console errors.
- [ ] Screenshots from that test, small, committed and shown.
- [ ] Your own
DataSourceandOperationsin production, proved with the conformance suite.