Skip to content

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.

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, and pages/ run in the App worker and browser — they never see process environment variables unless explicitly allowlisted in mistri.json, and they never hold secrets.
  • mistri.json, commands.ts, jobs.ts, policy.ts, routes/, and middleware.ts are 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 --fix to 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, and CHECK (status IN (...)) constraints in migrations/V1__….sql. Mistri introspects those constraints to build relationships, reference pickers, status vocabularies (including single-value CHECK (col = 'only')), and strict string-literal unions in mistri-schema.d.ts.
  • Add an integer version column (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, and mistri check’s query EXPLAIN and 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, and mistri check --pending to 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).

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
commands.ts
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 })):

mistri.json
{
"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}" }
}
]
}
commands.ts
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’s lookup phase (which runs before the DB transaction opens), then persist the result inside handle:
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.ts with defineJob (with per-job leaseMs / 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 integration secrets in defineIntegration. 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:
    1. Enable "forwardTokens": true and list the required "scopes" (include "offline_access" if your provider requires it to issue a refresh_token) on your "kind": "oidc" provider in mistri.json. Production requires MISTRI_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 via refresh_token rotation within a 60-second expiry window (Identity providers).
    2. Consume the delegated token in whichever server surface calls the upstream API:
      • "kind": "http" OpenAPI sources: set "forwardUserBearer": "<provider-id>" (or true for the signed-in user’s forwardable OIDC provider) on the connection. Mistri attaches Authorization: Bearer <token>, bypasses shared response caches and cursor walks so responses never leak across users, and refuses anonymous or tokenless reads with 401 (Connections and services).
      • defineIntegration actions: call await userToken?.() (or await userToken?.('<provider-id>')) inside actions.<name>.run(client, input, { idempotencyKey, signal, userToken }). userToken is provided for interactive signed-in commands and is undefined in background jobs, workflows, and webhooks (Integrations).
      • defineRoute handlers: call await userToken() (or await userToken('<provider-id>')) from the route handler context; it returns undefined when anonymous or unavailable (SSR, ISR, routes and middleware).
mistri.json
{
"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/:

routes/feed.xml.route.ts
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>`);
},
});
routes/webhooks/stripe.route.ts
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 .):

app.ts
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, cards for visual items, board for state-machine workflows, queue for inbox triage, calendar / gantt / tree / split where the shape fits.
  • Record pages: follow the standard skeleton — header({ status, facts }), a summary of 3–4 rollups, tabbed related child lists (listTabs: true), and an aside with parent card, current, properties, and history().
  • Dashboards: 3–4 headline metric cards (over + better), time-series chart, breakdown / matrix, and action queues under shared windows.
  • Documents: printable invoices, quotes, and receipts with @page running 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/child include, get clean /<page>/<id>-<slug> URLs automatically (when the resource sets slug: true and recordLabel), and feed the exact preloaded record to both seo({ record }) (title, description, Open Graph, JSON-LD) and component({ record }) — no boilerplate loader required.
  • Declarative collection pages (definePage({ path, rows })): declare static, :param, or *rest routes (path: '/category/:slug') with single or named-map parallel rows preloads.
  • Complex or multi-source server reads (defineLoader): use a loader in commands.ts when 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: [...] } on auth.public or definePage({ public: true }) for ISR caching with automatic write invalidation and CDN headers.
    • Signed-out visitors on public definePage routes automatically receive the lean site JS 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, use ui.redirects / ui.rewrites for static path rules, and add middleware.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 hidden on 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, and MISTRI_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 route link), set retention windows (including retention.reads), and stream read-audit rows to your SIEM with registerReadAuditStreamSink / createBatchedNdjsonAuditSink (Observe).

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)

Run the same five-step gate locally and in CI (and hand it directly to a coding agent via mistri agent init):

Terminal window
# 1. Develop with hot reload and an isolated .mistri/ dev auth store
npx @mistriwork/mistri dev --app .
# 2. Typecheck, validate DSL, EXPLAIN queries, check indexes, and lint design
npx @mistriwork/mistri check --app . --design --max-warnings 0
# 3. Inspect real screenshots (runs on a throwaway SQLite copy by default) and grade layout/contrast
npx @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 infrastructure
npx @mistriwork/mistri check --app . --deploy
npx @mistriwork/mistri build --app .
npx @mistriwork/mistri doctor --config mistri.json --live

When 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.