Skip to content

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/).

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):

examples/apps/foundry/app.ts
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/HEAD responses with no session cookie or auth-proxy header ever read from or write to the public HTML cache. Signed-in visitors always receive Cache-Control: private, no-store and never touch the shared cache.
  • CDN & revalidation headers: Emits Cache-Control: public, max-age=0, s-maxage=<fresh>, stale-while-revalidate=<stale>, strong ETag with 304 Not Modified, Cache-Tag / Surrogate-Key, and X-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([...]).

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:

examples/apps/foundry/pages/item.page.tsx
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.

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:

examples/apps/foundry/pages/_layout.tsx
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>;
},
});

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

examples/apps/foundry/routes/feed.xml.route.ts
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-only db restricted to declared reads, transactional writes exclusively through declared commands via await run('commandName', input) (audited and auto-invalidating ISR), plus invalidateTags([...]).
  • Delegated OIDC tokens (userToken): Alongside actor, params, query, db, and run, call await userToken() (or await userToken('<provider>')) to resolve the signed-in caller’s delegated OIDC bearer token when an OIDC provider enables "forwardTokens": true (returns undefined when anonymous or unavailable; see Identity providers).
  • Ergonomic responses: Return a plain object/array (auto-serialized as JSON), use json, text, html, xml, sse, redirect, or notFound, or return a standard Web Response.
  • Composable middleware: Pass middleware: [rateOrHeaderMiddleware] to run reusable defineMiddleware units before handle.

For external server-to-server POST callbacks (Stripe, GitHub, shipping providers), use defineWebhook instead of relaxing Origin checks on regular routes:

routes/webhooks/stripe.route.ts
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:

examples/apps/foundry/middleware.ts
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(...)).

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:

examples/apps/foundry/app.ts
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 site JS surface: Signed-out visitors opening interactive definePage({ public: true }) pages automatically receive index.site.html instead 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-in loads the full shell on demand.
  • Scoped i18n helper (useMessages): Multi-locale pages can bind const t = useMessages('item') once and call t('reserveCta') or t('monthlyNote', { amount }) inline anywhere in JSX.
  • Cache tags & programmatic invalidation: Cached responses configured with auth.public.cache or definePage({ cache }) emit Cache-Control, ETag, Cache-Tag, and Surrogate-Key headers (mistri:<app>, mistri:<app>:<table>, mistri:<app>:tag:<tag>) for downstream CDNs. Committed table writes invalidate matching entries automatically, and custom defineRoute or defineWebhook handlers can invalidate custom tags explicitly through invalidateTags([...]) on the handler context.
  • 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).