Build an App
Start with the lightest declaration that holds the invariant. Let your SQL schema and built-in views carry most of the App, and reach for state machines, transactional commands, custom pages, external HTTP sources, and custom routes only where the domain actually needs them.
1. Recommended project layout and trust boundary
Section titled “1. Recommended project layout and trust boundary”Keep every App in one directory split by concern and trust boundary:
my-app/├── mistri.json # Connections, services, env allowlist (server-only, ${ENV} refs)├── authority.lock # Attested connections, secrets, routes, webhooks, API surface├── migrations/│ └── V1__init.sql # Versioned SQL migrations (source of truth for tables & constraints)├── app.ts # defineApp(...): sources, auth, home, ui, api, live, assistant├── resources.ts # Resource access, machines, rollups, validations, audit rules├── views.ts # listView, commandForm, landing├── dashboards.ts # dashboard(...): metrics, charts, breakdowns, windows├── navigation.ts # navGroup(...) sidebar/topbar structure├── pages/│ ├── _layout.tsx # Optional nested layout (defineLayout) wrapping non-bare pages│ ├── order.ts # Built-in record page (page('order', [...]))│ ├── catalog.page.tsx # Free-form / public collection page (definePage({ path, rows }))│ └── item.page.tsx # Declarative detail page (definePage({ path, record, seo, cache }))├── commands.ts # Server-only: defineCommands(...) & defineLoaders(...)├── jobs.ts # Server-only: defineJobs(...), defineWorkflows(...), integrations├── policy.ts # Server-only (optional): row policies (definePolicy) or tenant policy├── routes/│ ├── feed.xml.route.ts # Server-only: custom HTTP endpoint (defineRoute)│ └── webhooks/│ └── stripe.route.ts # Server-only: HMAC-verified inbound webhook (defineWebhook)├── middleware.ts # Server-only (optional): scoped request middleware (defineMiddleware)├── messages/│ ├── en.json # Default locale messages & framework word overrides (mistri.*)│ └── es.json # Additional locales└── mistri-schema.d.ts # Generated by `mistri check` (alongside mistri-commands/components.d.ts)Respect the trust boundary:
app.ts, its imported declaration modules, andpages/run in the App worker and browser — they never see process environment variables unless explicitly allowlisted inmistri.json, and they never hold secrets.mistri.json,commands.ts,jobs.ts,policy.ts,routes/, andmiddleware.tsare server-only. Put database writes, secret credentials, webhook signature verification, and external API calls there.- Keep declarations thin: Mistri infers labels, money/date formats, column widths, default sort orders, and record page layouts from the schema (Conventions). Run
mistri check --design --fixto strip restated rules.
2. Data model, migrations, and multi-source topology
Section titled “2. Data model, migrations, and multi-source topology”Put data integrity in SQL first:
- Declare
PRIMARY KEY,FOREIGN KEY,NOT NULL,UNIQUE, andCHECK (status IN (...))constraints inmigrations/V1__….sql. Mistri introspects those constraints to build relationships, reference pickers, status vocabularies (including single-valueCHECK (col = 'only')), and strict string-literal unions inmistri-schema.d.ts. - Add an integer
versioncolumn (version INTEGER NOT NULL DEFAULT 0) on tables mutated by commands so revision-checked concurrency catches stale edits (409 stale_record). - Use PostgreSQL for production, multi-worker processes (
--workers), row policies, multi-tenant Apps, andmistri check’s queryEXPLAINand missing-index checks. Use SQLite for local development, prototypes, and single-writer tools. - Manage schema evolution through versioned migrations (
mistri migrate diff,mistri migrate up, andmistri check --pendingto verify the App against pending migrations on a scratch copy before applying). See Change your schema.
Multi-source topology:
- Prefer one PostgreSQL connection with multiple schemas (
ops: { connection: 'main', schema: 'ops' },catalog: { connection: 'main', schema: 'catalog' }) whenever tables live in the same database — joins and transactions stay atomic. - Add a second connection only when data lives in another database or an external HTTP service (Sources). Tables on the default source stay bare (
order); secondary source tables are prefixed (carrier.shipments).
3. Choose the lightest write path
Section titled “3. Choose the lightest write path”Move down this ladder only when the lighter option cannot enforce the business rule:
| Level | Mechanism | Use when | Avoid when |
|---|---|---|---|
| 1 | Resource form (access: 'write') + validation |
Creating or editing a record’s own columns, validated by SQL constraints and same-row { must, when, message } rules |
The write depends on other tables, stored history, or who is acting |
| 2 | Fixed action (set + when) |
One-click column changes (archive, reopen) with optional confirm |
You need enforced state transitions or multi-row logic |
| 3 | State machine |
An ordered lifecycle with legal transitions, board lanes, record stepper, final: true terminal states, and confirm: { title, body, yes } |
Status can be edited freely or transitions require side effects across tables |
| 4 | defineCommand (commands.ts) |
Multi-table atomic transactions, stock/overlap guards, external API lookups, initial() prefills, refuse('…') (command_refused 422), or emitted domain events |
A resource form or fixed action is enough |
import { defineCommand, defineCommands, field, refuse, shape, text } from '@mistriwork/mistri/commands';import type { Rows } from './mistri-schema.d.ts';
export const commands = defineCommands({ approveOrder: defineCommand<Rows>({ source: 'main', target: 'order', read: ['order', 'inventory'], write: ['order', 'inventory'], input: { note: field.text({ optional: true, max: 300 }) }, output: shape({ status: text() }), async handle({ db, record }, input) { const stock = await db.inventory.where({ sku: record.sku }).first(); if (!stock || stock.available < record.quantity) refuse('Not enough stock on hand.'); await db.inventory.update(stock, { available: stock.available - record.quantity }); await db.order.update(record, { status: 'approved', note: input.note ?? null }); return { status: 'approved' }; }, }),});See Forms, Actions, and Commands.
4. External HTTP endpoints, webhooks, and APIs
Section titled “4. External HTTP endpoints, webhooks, and APIs”Mistri separates reading external HTTP APIs, calling external APIs during writes, serving custom HTTP endpoints / webhooks, and exposing a typed App API into four distinct patterns so each stays governed by authority.lock:
A. Read from an external HTTP/OpenAPI endpoint as a source ("kind": "http")
Section titled “A. Read from an external HTTP/OpenAPI endpoint as a source ("kind": "http")”Declare an external HTTP API as a read-only connection in mistri.json, bind it in app.ts under sources, and query it just like a database table — in built-in views, custom pages, or parallel multi-source loaders (defineLoader({ sources })):
{ "connections": [ { "name": "main", "url": "${DATABASE_URL}", "writable": true }, { "name": "carrier", "kind": "http", "url": "https://api.carrier.example/v1/", "description": "carrier.http.json", "auth": { "bearer": "${CARRIER_API_TOKEN}" } } ]}export const loaders = defineLoaders({ orderTracking: defineLoader({ reads: ['order'], sources: { carrier: ['shipments'], // read-only "kind": "http" OpenAPI source }, async load({ db, sources, params }) { const order = await db.order.where({ id: Number(params.id) }).first(); const shipment = order?.tracking_number ? await sources.carrier.shipments.where({ tracking_number: order.tracking_number }).first() : null; return { order, shipment }; }, }),});The HTTP adapter applies timeouts, retries, response limits, and per-role read grants automatically (Sources, Connections and services).
B. Call external HTTP services on write (defineIntegration + lookup or defineJob)
Section titled “B. Call external HTTP services on write (defineIntegration + lookup or defineJob)”Never hold a database transaction open across a slow third-party HTTP call:
- Synchronous external check or charge: declare an integration with
defineIntegration(@mistriwork/mistri/integration) and call it in a command’slookupphase (which runs before the DB transaction opens), then persist the result insidehandle:
chargeOrder: defineCommand({ source: 'main', target: 'order', input: {}, integrations: { billing: ['charge'] }, lookup: ({ record, integrations }) => integrations.billing.charge({ amount: record.total_cents, customer: record.customer_id }), handle: ({ db, record, lookup }) => db.order.update(record, { status: 'paid', charge_id: lookup.id }),}),- Asynchronous outbound calls & webhooks: emit an event from your command and process it in
jobs.tswithdefineJob(with per-jobleaseMs/timeoutMs, automatic backoff retries, idempotency keys, and dead-letter inspection). See Integrations and Events, jobs and workflows.
Outbound credentials: service credentials vs. delegated per-user OIDC tokens
Section titled “Outbound credentials: service credentials vs. delegated per-user OIDC tokens”Pick the credential model that matches how the upstream API authorizes callers:
- Service credentials (shared API keys or service tokens): configure
"auth": { "bearer": "${TOKEN}" }or{ "header": "x-api-key", "value": "${KEY}" }on a"kind": "http"connection, or store per-tenant integrationsecretsindefineIntegration. Service credentials work everywhere — interactive commands, background jobs, workflows, and webhooks. - Delegated per-user OIDC bearer token forwarding (Microsoft Entra ID, Azure AD B2C, Keycloak, Okta, or any standard OIDC provider): when the upstream API requires the signed-in user’s own bearer token:
- Enable
"forwardTokens": trueand list the required"scopes"(include"offline_access"if your provider requires it to issue arefresh_token) on your"kind": "oidc"provider inmistri.json. Production requiresMISTRI_SECRETS_KEY(32+ bytes); tokens are sealed at rest with AES-256-GCM on the server, never exposed to browsers or/api/auth/*, and refreshed automatically viarefresh_tokenrotation within a 60-second expiry window (Identity providers). - Consume the delegated token in whichever server surface calls the upstream API:
"kind": "http"OpenAPI sources: set"forwardUserBearer": "<provider-id>"(ortruefor the signed-in user’s forwardable OIDC provider) on the connection. Mistri attachesAuthorization: Bearer <token>, bypasses shared response caches and cursor walks so responses never leak across users, and refuses anonymous or tokenless reads with401(Connections and services).defineIntegrationactions: callawait userToken?.()(orawait userToken?.('<provider-id>')) insideactions.<name>.run(client, input, { idempotencyKey, signal, userToken }).userTokenis provided for interactive signed-in commands and isundefinedin background jobs, workflows, and webhooks (Integrations).defineRoutehandlers: callawait userToken()(orawait userToken('<provider-id>')) from the route handler context; it returnsundefinedwhen anonymous or unavailable (SSR, ISR, routes and middleware).
- Enable
{ "connections": [ { "name": "workforce", "kind": "oidc", "issuer": "https://login.microsoftonline.com/<tenant-id>/v2.0", "clientId": "<application-id>", "clientSecret": "${WORKFORCE_CLIENT_SECRET}", "scopes": ["offline_access", "api://<upstream-api-id>/records.read"], "forwardTokens": true }, { "name": "upstream", "kind": "http", "url": "https://api.upstream.example/v1/", "description": "upstream.http.json", "forwardUserBearer": "workforce" } ]}C. Expose custom HTTP endpoints and receive inbound webhooks (routes/**/*.route.ts)
Section titled “C. Expose custom HTTP endpoints and receive inbound webhooks (routes/**/*.route.ts)”For non-command HTTP endpoints (RSS/XML feeds, JSON payloads, CSV downloads, SSE streams) or external provider callbacks (Stripe, GitHub, shipping carriers), drop typed route modules under routes/:
import { defineRoute, defineSource } from '@mistriwork/mistri/commands';import type { Rows } from '../mistri-schema.d.ts';
const main = defineSource<Rows>('main');
export default defineRoute({ source: main, methods: ['GET', 'HEAD'], auth: 'public', reads: ['listing'], cache: { fresh: '5 minutes', stale: '15 minutes', tags: ['catalog:feed'] }, async handle({ db, xml }) { const rows = await db.listing.where({ status: 'live' }).orderBy('id', 'asc').limit(20); return xml(`<rss version="2.0"><channel><!-- ${rows.length} items --></channel></rss>`); },});import { defineSource, defineWebhook } from '@mistriwork/mistri/commands';import type { Rows } from '../../mistri-schema.d.ts';
const main = defineSource<Rows>('main');
export default defineWebhook({ source: main, role: 'webhook', // a `service: true` role in auth.roles granted `markOrderPaid` verify: { hmac: 'sha256', header: 'x-hub-signature-256', secret: 'STRIPE_WEBHOOK_SECRET', prefix: 'sha256=', }, reads: ['order'], commands: ['markOrderPaid'], async handle({ bodyJson, run, invalidateTags }) { const event = bodyJson<{ orderId: number }>(); await run('markOrderPaid', { orderId: event.orderId }); await invalidateTags(['catalog:feed']); return { received: true }; },});Every defineRoute and defineWebhook is attested in authority.lock, strips session cookies on webhooks, verifies raw body bytes with timing-safe HMAC, and routes all writes through transactional commands (automatically invalidating ISR cache tags). Note that routes/*.route.ts and middleware.ts are for standalone non-tenant, non-row-policy Apps — for tenant Apps or row-policy Apps, use defineIntegration webhooks or mount the App in your own Node server (SSR, ISR, routes and middleware).
D. Expose a versioned App HTTP API (api DSL)
Section titled “D. Expose a versioned App HTTP API (api DSL)”When external services, mobile apps, or partners need typed programmatic access to your resources, commands, and events, declare api directly in app.ts (or scaffold it with npx @mistriwork/mistri api init --app .):
api: { version: 1, integers: 'decimal-string', requestsPerMinute: 120, explorer: true, roles: ['partner'], resources: { order: expose('order', { read: true, fields: ['id', 'status', 'total_cents'] }), }, commands: ['approveOrder'], events: ['order.approved'],},Declaring api automatically serves /api/apps/<id>/v1/*, OpenAPI JSON & YAML (/$openapi, /$openapi.yaml), AsyncAPI (/$asyncapi), and the self-hosted Explorer (/$docs). Generate a zero-import typed client (mistri api client) and issue scoped tokens (mistri api-token issue). See App HTTP API and An API-only App.
5. Screens, custom pages, SSR, ISR, and loaders
Section titled “5. Screens, custom pages, SSR, ISR, and loaders”Start with built-in views for internal workflows:
- Lists: default grid for scanning/comparing,
cardsfor visual items,boardfor state-machine workflows,queuefor inbox triage,calendar/gantt/tree/splitwhere the shape fits. - Record pages: follow the standard skeleton —
header({ status, facts }), asummaryof 3–4 rollups, tabbedrelatedchild lists (listTabs: true), and an aside with parentcard,current,properties, andhistory(). - Dashboards: 3–4 headline
metriccards (over+better), time-serieschart,breakdown/matrix, and action queues under sharedwindows. - Documents: printable invoices, quotes, and receipts with
@pagerunning headers and dot-prefixed address joining.
Reach for pages/*.page.tsx (definePage) when you need a public storefront, custom interactive screen, dynamic URL, or custom SEO:
- Declarative detail pages (
definePage({ record })): bind a primary resource with optional parent/childinclude, get clean/<page>/<id>-<slug>URLs automatically (when the resource setsslug: trueandrecordLabel), and feed the exact preloaded record to bothseo({ record })(title, description, Open Graph, JSON-LD) andcomponent({ record })— no boilerplate loader required. - Declarative collection pages (
definePage({ path, rows })): declare static,:param, or*restroutes (path: '/category/:slug') with single or named-map parallelrowspreloads. - Complex or multi-source server reads (
defineLoader): use a loader incommands.tswhen a page aggregates across databases, queries a"kind": "http"OpenAPI source, or shapes custom server payloads. - SSR & caching (
render&cache):render: 'stream'(default) streams SSR HTML with<Suspense>and a per-request CSP nonce for both public and signed-in pages.render: 'static'emits zero-JS public HTML (script-src 'none').render: 'client'opts out of SSR for heavy client-only canvases.- Add
cache: { fresh: '2 minutes', stale: '10 minutes', tags: [...] }onauth.publicordefinePage({ public: true })for ISR caching with automatic write invalidation and CDN headers. - Signed-out visitors on public
definePageroutes automatically receive the leansiteJS bundle (index.site.html), keeping the staff workspace chrome off the public path.
- Shared chrome & routing: place
pages/_layout.tsx(defineLayout({ reads?, optionalReads?, component })) to wrap non-bare pages across SSR and SPA navigation, useui.redirects/ui.rewritesfor static path rules, and addmiddleware.ts(defineMiddleware) for per-request headers or conditional redirects.
See SSR, ISR, routes and middleware, Custom components, and Choose a building block.
6. Access posture, tenancy, secrets, and audit
Section titled “6. Access posture, tenancy, secrets, and audit”Pick the App’s access model early — changing it alters authority.lock:
| Posture | Configure | Best for |
|---|---|---|
| Internal tool | auth.roles + column fields |
Company operations where roles control tables, columns, and commands (Roles) |
| Row-policy App | auth.roles + policy.ts (owner_id = me.id, via(...) trees) |
Multi-team or customer-scoped Apps sharing one database (Row access) |
| Multi-tenant SaaS | tenant + platform realms, PostgreSQL RLS backstop, per-tenant invitations/branding/domains/mail |
B2B SaaS with strict per-tenant isolation and support elevation audits (Tenant Apps) |
| Public + Staff hybrid | auth.public allowlist + signed-in auth.roles |
Marketplaces, portals, and storefronts where anonymous visitors browse and staff manage operations (Public pages) |
Security and audit defaults to turn on before launch:
- Hide sensitive columns with
hiddenon the connection or resource (mistri.json/resources.ts), and keep credentials in${VARIABLE}references only. - Provision separate 32+ byte server sealing keys in production:
BETTER_AUTH_SECRET,MISTRI_SECRETS_KEY,MISTRI_FORM_KEY,MISTRI_AUDIT_KEY, andMISTRI_CACHE_KEY(Secrets and hidden columns). - Enable
audit: { reads: true, redact: ['ssn'] }on sensitive resources (audited across pages, APIs, MCP, exports, commands, and capability links under routelink), setretentionwindows (includingretention.reads), and stream read-audit rows to your SIEM withregisterReadAuditStreamSink/createBatchedNdjsonAuditSink(Observe).
7. Other major platform capabilities
Section titled “7. Other major platform capabilities”Turn these on declaratively as your App grows:
| Capability | Where you declare it | What it gives you |
|---|---|---|
| Events, jobs & durable workflows | events in commands.ts; defineJob & defineWorkflow in jobs.ts |
Transactional outbox, exponential backoff retries, per-job leaseMs/timeoutMs, multi-step workflows, and dead-letter redrive (Events, jobs and workflows) |
| Live sync | live: true in app.ts (+ Valkey in mistri.json for multi-worker) |
Real-time invalidation of open lists, dashboards, and record pages across browsers (Live sync) |
| Looks, themes & i18n | ui.theme (11 built-in looks, 14 palettes, defineTheme), messages/*.json |
Branded UI with WCAG contrast checks, dark mode, and localized strings via useMessage / useMessages (Looks, Themes, Languages) |
| Embedded AI assistant | assistant in app.ts + provider key (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, or OpenAI-compatible URL) |
Read-scoped assistant and specialist subagents bound to the signed-in caller’s exact grants, plus useAssistantContext for page state (An assistant) |
| Decisions, flags, experiments & analytics | defineDecision, flags, experiments, analytics |
Audited business rule tables, feature rollouts, A/B assignments, and first-party kebab-case product events (useAnalytics().emit(...)) (Decisions, Experiments, Analytics) |
8. The build, verify, and ship loop
Section titled “8. The build, verify, and ship loop”Run the same five-step gate locally and in CI (and hand it directly to a coding agent via mistri agent init):
# 1. Develop with hot reload and an isolated .mistri/ dev auth storenpx @mistriwork/mistri dev --app .
# 2. Typecheck, validate DSL, EXPLAIN queries, check indexes, and lint designnpx @mistriwork/mistri check --app . --design --max-warnings 0
# 3. Inspect real screenshots (runs on a throwaway SQLite copy by default) and grade layout/contrastnpx @mistriwork/mistri shot --app .npx @mistriwork/mistri grade --app .
# 4. Run automated command, HTTP, and browser tests# Use createTestHost + createTestClient<Rows, Commands> (+ host.resetLimits() between cases)npm test
# 5. Preflight deployment, build standalone output/Dockerfile, and verify live infrastructurenpx @mistriwork/mistri check --app . --deploynpx @mistriwork/mistri build --app .npx @mistriwork/mistri doctor --config mistri.json --liveWhen check or a runtime response returns a code you want explained, run npx @mistriwork/mistri explain <code> — it explains both static check codes and HTTP/command runtime refusal codes (invalid_result, ineligible_state, stale_record, forbidden, etc.) with the fix.
Related
Section titled “Related”- Choose a building block: side-by-side matrix of when to pick each view, section, command, route, or cache option.
- The DSL in one App: every declaration read directly off a working sample.
- SSR, ISR, routes and middleware: deep dive into caching, streaming SSR,
definePage({ path, record, rows }),defineRoute,defineWebhook, anddefineMiddleware. - Sample Apps: explore Tick, Lintel, Ladle, and Foundry Market end to end.
- Build an App with a coding agent: agent setup, brief, and acceptance rubric.
- Test an App and Testing workflow: test harness and Playwright patterns.
- Build and deploy: production runtime, secrets, workers, and containers.