SSR, ISR, routes and middleware
Cache public HTML with automatic invalidation, stream SSR for public and signed-in pages, emit dynamic SEO and JSON-LD, nest layouts, and author custom routes, webhooks, and middleware — all in a standalone App with zero mandatory build step.
See every feature below working together in Foundry Market (examples/apps/foundry/).
Public HTML caching (ISR)
Section titled “Public HTML caching (ISR)”Add cache using Mistri’s Duration grammar ('30 seconds', '2 minutes', '10 minutes', '1 hour') on auth.public (for built-in public pages) or on any definePage({ public: true }) (or public defineRoute):
auth: { public: { read: ['listing', 'listing_photo', 'seller'], cache: { fresh: '2 minutes', stale: '10 minutes', tags: ['foundry'] }, },}Or use the shorthand on a single page:
export default definePage({ public: true, reads: ['listing'], cache: '2 minutes', // or { fresh: '2 minutes', stale: '10 minutes', tags: ['foundry:door'] } component: DoorPage,});What the server handles automatically:
- Strict anonymity gate: Only anonymous
GET/HEADresponses with no session cookie or auth-proxy header ever read from or write to the public HTML cache. Signed-in visitors always receiveCache-Control: private, no-storeand never touch the shared cache. - CDN & revalidation headers: Emits
Cache-Control: public, max-age=0, s-maxage=<fresh>, stale-while-revalidate=<stale>, strongETagwith304 Not Modified,Cache-Tag/Surrogate-Key, andX-Mistri-Cache: HIT | STALE | MISS. - Automatic write invalidation: Any committed record edit, command run, webhook command, or CSV import bumps the version epoch for the mutated tables (and broadcasts via Valkey Pub/Sub when a shared cache service is configured), and custom routes or webhooks can invalidate custom tags explicitly with
invalidateTags([...]).
Render modes and streaming SSR
Section titled “Render modes and streaming SSR”Every free-form definePage supports a unified render mode:
| Mode | Scope | Behavior |
|---|---|---|
'stream' (default) |
Public & signed-in | SSR + progressive <Suspense> streaming (onShellReady) with a per-request 128-bit CSP nonce. Signed-in pages stream under the caller’s real RBAC and row-policy grants with Cache-Control: private, no-store. |
'static' |
Public pages without commands/forms | Zero-JS static HTML (script-src 'none', strips executable <script> and modulepreload tags while preserving CSS and JSON-LD). |
'client' |
Public & signed-in | Skips server-side React rendering for heavy client-only canvases. |
export default definePage({ public: true, render: 'static', // zero client JS, strict script-src 'none' cache: { fresh: '10 minutes', stale: '1 hour' }, reads: ['article'], component: EditorialPage,});Declarative record binding & co-located SEO / JSON-LD
Section titled “Declarative record binding & co-located SEO / JSON-LD”For detail pages (product pages, vehicle detail pages, profiles), declare record directly on definePage so the page preloads its primary record (with optional parent LEFT JOINs and bounded 1-to-many child includes) in one round trip and feeds the exact same typed record to both dynamic seo({ record, data, params }) and the component — no separate commands.ts loader needed:
export default definePage({ public: true, reads: ['listing_photo', 'seller'], // 'listing' and params.id are inferred from `record` record: { from: 'listing', show: ['id', 'title', 'maker', 'category', 'year_made', 'price_cents', 'status', 'description'], include: { seller: { via: 'seller_id', show: ['id', 'name', 'city', 'specialty', 'bio'] }, }, }, cache: { fresh: '2 minutes', stale: '10 minutes', tags: ['foundry:item'] }, seo({ record: item }) { if (!item) return { title: 'Piece not found — Foundry Market', robots: 'noindex' }; return { title: `${item.title} — ${item.maker} (${item.year_made}) | Foundry Market`, description: item.description, type: 'article', ...(item.cover ? { image: item.cover } : {}), jsonLd: { '@context': 'https://schema.org', '@type': 'Product', name: item.title, brand: { '@type': 'Brand', name: item.maker }, offers: { '@type': 'Offer', price: (item.price_cents / 100).toFixed(2), priceCurrency: 'USD', ...(item.seller?.name ? { seller: { '@type': 'Organization', name: item.seller.name } } : {}), }, }, }; }, component: ({ record: item }) => { // `item` is preloaded during SSR and typed with `item.seller?.name` and `item.cover` return item ? <h1>{item.title}</h1> : null; },});When a page instead uses a server loader, seo({ data, params }) receives the loader’s typed data with zero duplicate database queries. JSON-LD is emitted in an escaped <script type="application/ld+json"> tag without loosening CSP (script-src never adds 'unsafe-inline'), and client-side SPA navigations keep document.title and <meta name="description"> in sync with seo(...) automatically.
Clean record paths, slugs & dynamic path routes: Any definePage({ record: { from } }) automatically gets clean path routing (/<page>/<id>, or /<page>/<id>-<slug> when the resource sets slug: true and recordLabel in app.ts), and infers from in reads and param (default 'id') in params. To declare a custom URL pattern directly on the page — including multi-segment paths, dynamic :param segments, or a trailing *rest catch-all — pass path to definePage:
export default definePage({ label: 'Category', path: '/category/:slug', // or '/pieces/:category/:id' (with `record`) or '/docs/*slug' public: true, rows: { from: 'listing', // automatically added to `reads` where: ({ params }) => ({ status: 'live', category: params.slug }), // return `false` to skip querying show: ['id', 'title', 'price_cents'], sort: 'id asc', }, seo({ params: { slug }, rows }) { return { title: `${slug} (${rows.length}) — Foundry Market` }; }, component({ params: { slug }, rows }) { // `slug` is typed as `string` from `path`; `rows` is preloaded during SSR and SPA navigation return <h1>{slug}: {rows.length} pieces</h1>; },});Need multiple collections on one page? Pass a named map to rows (rows: { listings: { from: 'listing', ... }, sellers: { from: 'seller', ... } }) — every query runs in parallel, each from table is auto-added to reads, and seo / component receive { rows: { listings, sellers } }. Link with href.record('item', row) or href.page('category', { slug: 'cameras' }) — path parameters are interpolated into the URL automatically, extra params remain in the query string, bare record URLs 301-redirect to their canonical slugged path, and missing records invoke seo({ record: null }) so you can return robots: 'noindex'. Pages needing interactive client-side filtering can still omit rows and call page.useRows(...) / page.useParam(...) directly.
Nested layouts (pages/**/_layout.tsx)
Section titled “Nested layouts (pages/**/_layout.tsx)”Place _layout.tsx in pages/ (or any subdirectory) exporting defineLayout({ reads?, optionalReads?, bare?, component }). Layouts compose outer-to-inner around every non-bare free-form page beneath them during both SSR and client SPA navigation (receiving { children, path }), and setting bare: true opts a layout into wrapping layout: 'bare' pages as well. Their reads are checked against auth.public when wrapping public pages:
import type { ReactNode } from 'react';import { defineLayout } from '@mistriwork/mistri/page';
export default defineLayout({ component({ children }: { readonly children: ReactNode }) { return <div data-foundry-layout="storefront">{children}</div>; },});Custom HTTP routes (routes/**/*.route.ts)
Section titled “Custom HTTP routes (routes/**/*.route.ts)”Author custom endpoints (RSS/XML feeds, JSON APIs, CSV exports, SSE streams) under routes/ using defineRoute from @mistriwork/mistri/commands. File paths support static segments, [param], and [...rest].
import { defineRoute, defineSource } from '@mistriwork/mistri/commands';import type { Rows } from '../mistri-schema.d.ts';
const foundry = defineSource<Rows>('foundry');
export default defineRoute({ source: foundry, methods: ['GET', 'HEAD'], auth: 'public', reads: ['listing'], cache: { fresh: '5 minutes', stale: '15 minutes', tags: ['foundry:feed'] }, async handle({ db, xml }) { const listings = await db.listing.where({ status: 'live' }).orderBy('id', 'asc').limit(20); return xml(`<rss version="2.0"><channel><!-- ${listings.length} items --></channel></rss>`); },});Handler context highlights:
- Authority enforced:
auth: 'public' | 'signedIn' | { roles: [...] }, read-onlydbrestricted to declaredreads, transactional writes exclusively through declaredcommandsviaawait run('commandName', input)(audited and auto-invalidating ISR), plusinvalidateTags([...]). - Delegated OIDC tokens (
userToken): Alongsideactor,params,query,db, andrun, callawait userToken()(orawait userToken('<provider>')) to resolve the signed-in caller’s delegated OIDC bearer token when an OIDC provider enables"forwardTokens": true(returnsundefinedwhen anonymous or unavailable; see Identity providers). - Ergonomic responses: Return a plain object/array (auto-serialized as JSON), use
json,text,html,xml,sse,redirect, ornotFound, or return a standard WebResponse. - Composable middleware: Pass
middleware: [rateOrHeaderMiddleware]to run reusabledefineMiddlewareunits beforehandle.
First-class webhooks (defineWebhook)
Section titled “First-class webhooks (defineWebhook)”For external server-to-server POST callbacks (Stripe, GitHub, shipping providers), use defineWebhook instead of relaxing Origin checks on regular routes:
import { defineWebhook, defineSource } from '@mistriwork/mistri/commands';import type { Rows } from '../../mistri-schema.d.ts';
const app = defineSource<Rows>('app');
export default defineWebhook({ source: app, verify: { hmac: 'sha256', header: 'x-hub-signature-256', secret: 'WEBHOOK_SECRET', prefix: 'sha256=', }, reads: ['order'], commands: ['markOrderPaid'], async handle({ bodyJson, run }) { const event = bodyJson<{ orderId: number }>(); await run('markOrderPaid', { orderId: event.orderId }); return { received: true }; },});Every defineWebhook strips session cookies automatically, verifies raw body bytes with timing-safe HMAC-SHA256/512 (or a custom async verifier returning boolean), rejects invalid signatures with 401, and is attested in authority.lock. Calling run(commandName, ...) in a webhook handler requires either a service: true role in auth.roles granted that command — specifying role: '<serviceRole>' in defineWebhook when multiple service roles exist — or a public: true command; otherwise the call is refused with 403.
Custom routes (routes/*.route.ts using defineRoute or defineWebhook) and middleware.ts are not served on tenant Apps or row-policy Apps.
Scoped, env-aware middleware (middleware.ts)
Section titled “Scoped, env-aware middleware (middleware.ts)”Add middleware.ts beside app.ts (or pass middleware into defineRoute({ middleware: [...] })). Middleware always runs after Mistri’s security door, never runs on /api/*, cannot bypass RBAC or row policies, and cannot strip platform CSP or framing headers.
match accepts either a list of path patterns or a dynamic per-request predicate with ctx.env, ctx.path, ctx.method, ctx.headers, ctx.cookies, and ctx.actor:
import { defineMiddleware } from '@mistriwork/mistri/commands';
export default defineMiddleware({ match: ({ path, env }) => env.FOUNDRY_DISABLE_HEADERS !== 'true' && !path.startsWith('/sign-in'), handle({ env, header }) { header('X-Foundry-Edition', env.FOUNDRY_EDITION ?? 'gallery'); },});Short-circuit when needed with return redirect('/maintenance', 307), return rewrite('/alt-page'), or return respond(new Response(...)).
Enhanced redirects and rewrites
Section titled “Enhanced redirects and rewrites”In app.ts, ui.redirects accepts status codes (301, 302, 307, 308), trailing * wildcards, and vetted https:// destinations (attested in authority.lock), while ui.rewrites aliases internal paths without changing the browser URL:
ui: { redirects: { '/shop/*': { to: '/browse', status: 301 }, }, rewrites: { '/collection': '/browse', },}Multi-source page loaders (defineLoader({ sources }))
Section titled “Multi-source page loaders (defineLoader({ sources }))”Read-only server loaders can query the primary database (db) alongside any number of secondary databases or "kind": "http" OpenAPI sources (sources.<alias>) in parallel, under the same per-reader grants, field projection, timeout, and automatic mistri-reads tracking:
export const loaders = defineLoaders({ orderOverview: defineLoader({ reads: ['order', 'order.total'], sources: { carrier: ['shipments'], // "kind": "http" OpenAPI source billing: { source: billing, reads: ['invoice'] }, // second database }, async load({ db, sources, params }) { const order = await db.order.where({ id: Number(params.id) }).first(); const [shipment, invoices] = await Promise.all([ sources.carrier.shipments.where({ tracking_number: order?.tracking_number }).first(), sources.billing.invoice.where({ order_id: order?.id }).limit(10), ]); return { order, shipment, invoices }; }, }),});Lean public site bundle & cache tags
Section titled “Lean public site bundle & cache tags”- Lean
siteJS surface: Signed-out visitors opening interactivedefinePage({ public: true })pages automatically receiveindex.site.htmlinstead of the staff shell (app.js,appnav.js), keeping the workspace chrome, Grid, RecordPage, and CommandPalette off the public path (~43% smaller compressed JS). Navigating to a built-in room or/sign-inloads the full shell on demand. - Scoped i18n helper (
useMessages): Multi-locale pages can bindconst t = useMessages('item')once and callt('reserveCta')ort('monthlyNote', { amount })inline anywhere in JSX. - Cache tags & programmatic invalidation: Cached responses configured with
auth.public.cacheordefinePage({ cache })emitCache-Control,ETag,Cache-Tag, andSurrogate-Keyheaders (mistri:<app>,mistri:<app>:<table>,mistri:<app>:tag:<tag>) for downstream CDNs. Committed table writes invalidate matching entries automatically, and customdefineRouteordefineWebhookhandlers can invalidate custom tags explicitly throughinvalidateTags([...])on the handler context.
Related
Section titled “Related”- Build an App: recommended architecture, folder layout, external HTTP sources, and platform patterns.
- Public pages:
ui.site,preset: 'gallery', share cards, and sitemaps. - Sample Apps: run Foundry Market locally.
- Commands: writing transactional commands and page loaders.
- mistri check: validation codes (
layout-file,middleware-file,route-file,route-auth,route-reads,route-commands,route-clash).