Pages
Brix pages pair a browser-safe contract with a Preact component and a server route, giving SSR and URL construction one typed source of truth.
File layout
#From a full-stack application, generate the page before editing it:
brix add page productDetails --feature catalog
src/features/catalog/pages/productDetails/
contract.ts
Page.tsx
route.ts
route.test.ts
The conventional route.ts is discovered automatically; there is no route registry to update. It
must export exactly one runtime value whose lower-camel name ends in PageRoute.
Define the contract
#Contracts define paths and optional query validation:
import { createPageContract } from "#brix";
import { z } from "brix/zod";
export const productDetailsPageContract = createPageContract({
path: "/products/:productId",
query: z.object({ preview: z.string().optional() }),
});
contract.ts exports exactly one runtime value, the *PageContract; move shared schemas to a
separate module. Path parameters are inferred from :productId. Invalid query input receives a 400
response before the loader runs. Every query field must accept URL strings; see
query schemas.
Write the component
#The page module exports exactly one named runtime component ending in Page:
type ProductDetailsPageProps = {
product: { id: string; name: string };
};
export function ProductDetailsPage({ product }: ProductDetailsPageProps) {
return (
<main>
<h1>{product.name}</h1>
<p>Product ID: {product.id}</p>
</main>
);
}
Type-only exports are allowed. Do not use a default export or add unrelated runtime exports.
Create the route
#The loader receives parsed params and query and returns component props or an early Response:
import { createPageRoute } from "#brix/server";
import { ProductDetailsPage } from "./Page.tsx";
import { productDetailsPageContract } from "./contract.ts";
const products = new Map([["sku-123", { id: "sku-123", name: "Everyday backpack" }]]);
export const productDetailsPageRoute = createPageRoute(productDetailsPageContract, {
component: ProductDetailsPage,
load: (c, { params }) => {
const product = products.get(params.productId);
if (!product) return c.notFound();
return { product };
},
});
Start the development server and open /products/sku-123. The server runs the loader and returns an
HTML page headed Everyday backpack. Opening an unknown product path follows the application's 404
handling; no client-side fetch or route registration is required.
A request runs authentication, route middleware, query validation, load, and then render, in
that order. A loader may return any Response, such as c.redirect(...) or c.notFound(), to skip
rendering. When every component prop is optional, load can be omitted.
Headers that the loader or route middleware set before rendering stay on the rendered page, except
body validators: ETag, Last-Modified, Content-Length, Content-MD5, Content-Digest,
Digest, and Repr-Digest are removed. The rendered HTML carries a per-request CSP nonce by
default and may be composed or negotiated, so a validator computed from loader data would not
describe its bytes. To serve validators, set them in route middleware after
await next(), where they describe the rendered response, or return your own Response from
load, which keeps its headers. Brix does not answer conditional requests itself.
Set auth: true only after configuring authentication in defineBrixServer; see
authentication. Pass auth: { redirectUrl: (c) => "/login" } to
give the authentication middleware a page-specific sign-in destination. Authenticated pages cannot
declare a shared cache policy, and their responses receive Cache-Control: private unless the
page sets its own value.
A page with a plain string path receives locale: undefined in load. When it still needs the
resolved request locale, destructure getLocale from brixServer in src/brix.server.ts and call
getLocale(c).
Load remote data
#Replace the in-memory example with a request-scoped client when the page reads an API. Define
getCatalogClient once in a server-only module as shown in API clients,
then import the accessor into the route. This example assumes your getProductApiContract takes
productId and returns the page's { id, name } product:
import { createPageRoute } from "#brix/server";
import { getCatalogClient } from "#/features/catalog/catalog-client.server.ts";
import { getProductApiContract } from "#/features/catalog/api/getProduct/contract.ts";
import { ProductDetailsPage } from "./Page.tsx";
import { productDetailsPageContract } from "./contract.ts";
export const productDetailsPageRoute = createPageRoute(productDetailsPageContract, {
component: ProductDetailsPage,
load: async (c, { params }) => {
const result = await getCatalogClient(c).execute(getProductApiContract, {
params: { productId: params.productId },
});
if (result.isErr()) {
if (result.error.status === 404) return c.notFound();
return c.text("Catalogue unavailable", 502);
}
return { product: result.value };
},
});
Choose the page's failure presentation deliberately; this example maps an upstream 404 to not-found
and other failures to a generic 502 without exposing upstream details. The same accessor works in
authenticated loaders and API handlers. Do not recreate createService inside load, cast c, or
share a request-bound client globally. Return props rather than calling render. Request-scoped
service reuse is not response caching or authorization; configure those separately.
Start independent reads together
#Inside load, start independent reads before awaiting their results. Authentication and route
middleware still finish before load runs. Keep reads sequential when the second needs a value
or an authorization decision from the first; do not parallelize writes just to shorten a loader.
For example, extend the product page with an available: boolean prop and a
getAvailabilityApiContract that accepts the same productId and returns { available: boolean }.
Import that contract alongside getProductApiContract, then replace the loader with:
load: async (c, { params }) => {
const client = getCatalogClient(c);
const options = {
params: { productId: params.productId },
signal: c.req.raw.signal,
};
const [product, availability] = await Promise.all([
client.execute(getProductApiContract, options),
client.execute(getAvailabilityApiContract, options),
]);
if (product.isErr()) {
if (product.error.status === 404) return c.notFound();
return c.text("Catalogue unavailable", 502);
}
if (availability.isErr()) return c.text("Availability unavailable", 502);
return { product: product.value, available: availability.value.available };
},
These reads overlap rather than adding their network waits. Both are required here, so the loader
waits for both even when one returns an error. execute resolves to a Result: Promise.all does
not turn an Err into a rejection. Inspect every result before returning props, as above. For
optional data, choose an explicit fallback instead of treating a failed read as successful data.
createService reuses the client, not each call to its methods. Retain and reuse a read's promise
within load if several dependent operations need the same result; configure data caching
separately. Brix does not infer a dependency graph or automatically cancel sibling work when a
loader fails or returns an early response. Promise.all does not cancel siblings on rejection
either. Forward an AbortSignal to downstream reads; the example forwards the incoming request's
signal, but actual client-disconnect propagation depends on the runtime adapter. Page-owned early
cancellation requires an application-owned controller and signal-aware dependencies.
Build links safely
#Use getPath; do not concatenate path parameters manually:
import { getPath } from "#brix";
import { productDetailsPageContract } from "./contract.ts";
const href = getPath(productDetailsPageContract, {
params: { productId: "sku 123" },
query: { preview: "true" },
});
Brix encodes path values and serializes query schema input without running transforms or defaults;
incoming requests are parsed before the loader runs. Query options are required when schema input has
required keys. getPath also accepts API and response contracts, but only pages take an exact locale
key or Markdown representation.
Query schemas read URL strings
#Every query value arrives as a string or as repeated strings, so each field of a page, API,
response, or fragment query schema must accept string input. Declare numbers with
z.coerce.number(), booleans with z.stringbool(), dates with z.coerce.date() or
z.iso.datetime(), and string-first transforms such as z.string().transform(Number):
query: z.object({
page: z.coerce.number().int().min(1).default(1),
inStock: z.stringbool().optional(),
tags: z.array(z.string()).default([]),
}),
z.number(), z.boolean(), z.date(), nested objects, and nested arrays can never match a URL,
so contract creation rejects them with a TypeScript error and, for untyped code, a runtime error
naming the field. z.coerce.boolean() is rejected too because it reads "false" as true; inside
a field-level union without a string branch, or behind z.lazy(), only the runtime check catches it,
and a field-level union with a string branch is accepted. URLs
cannot carry null; use .optional() rather than .nullable(). A URL also cannot distinguish an
empty array from an absent key, so give array fields .default([]) or .optional() when an empty
list is valid. Callers pass the schema input: strings for string fields, and any string, number,
boolean, or bigint for coercing fields. Undefined and null values are omitted.
Coercion runs on the URL's string form (String(value)), not on the value the caller passed. Pass
ISO strings to z.coerce.date(): Date.now() sends digits that parse as an invalid date. Pass
numbers or numeric strings to z.coerce.number() and z.coerce.bigint(): true becomes NaN.
Direct route execution and the test harness use the same URL form, so these calls fail there too.
Every request carries a query object, even when the URL has no query string. A whole-schema
.optional(), .default(), or .prefault() therefore never applies, and contract creation
rejects one whose object has required fields. Make those fields optional or give them defaults.
Requiredness also applies to object unions such as { sku: string } | { barcode: string }, even
without a common key. A root preprocessor with unknown input accepts a flat record of URL values:
strings, numbers, booleans, bigints, and arrays of them. Nested objects are not URL values. Unknown input cannot express required keys, so omission is allowed by the types but
may fail server validation. Annotate the preprocessor's input when callers should retain precise
field types and requiredness; output validation alone cannot describe that input contract.
Singleton query values stay arrays for declared array fields, record values, and object catchalls,
including fields declared on either side of an intersection or behind z.lazy. Top-level object
unions normalize each branch independently, preserving Zod's first-success order; discriminated
unions use the wire discriminator. Unknown keys, including constructor, toString,
and __proto__, follow the schema's strip, strict, or catchall policy.
A scalar and a one-element array produce the same URL. Use a string-literal discriminator when union branches need different cardinalities for the same field. A field-level scalar/array union prefers the array representation. Put query-wide transforms after the object or union schema: arbitrary preprocessors before an undiscriminated union must normalize singleton cardinality explicitly. Empty arrays serialize to no key, not an empty-array marker.
Portable route paths
#For most pages, a literal path or a parameter such as :productId is enough. When you need
constraints, page and API routes use the same portable Hono path grammar so origin and edge
matching agree. Named parameters can use constraints such as /products/:productId{[0-9]+}.
Optional parameters must be terminal. Constraints cannot contain anchors, alternation, lookarounds,
or patterns that match an empty string; a constraint that can span slashes must be terminal.
Unsupported patterns are rejected during route registration rather than interpreted differently
by different routers.
Use query or body validation for data rules that do not belong in the URL structure. Use getPath
for URL construction rather than assembling constrained paths manually.
getPath preserves structural slashes for terminal wildcards and terminal named constraints that
can span /. For /tree/:path{[a-z/]+}, { path: "a/b" } produces /tree/a/b; ordinary parameters
and slash-free constraints encode the same value as a%2Fb. Each segment still encodes percent,
query, and fragment characters as data. Pass decoded values, not pre-encoded URLs. Dot-only
segments (. and ..) are rejected, including inside spanning values. A required parameter
cannot be an empty string, because /users/ would reach the /users route instead; an empty
optional parameter is omitted. Only a segment-leading colon declares a parameter, so
/v1/images:annotate is a static path.
Origin, edge matching, and locale preselection share Hono's non-strict pathname semantics: Unicode
and unreserved escapes decode for matching, encoded reserved separators and percent data remain
encoded, and one terminal slash is ignored. A literal /café therefore matches /caf%C3%A9.
Do not blanket-decode request paths or assume equivalent spellings share a cache entry.
Give locales their own paths
#If src/brix.ts configures locales: ["en-GB", "sv"] as const, replace the string path with a map:
export const productDetailsPageContract = createPageContract({
path: {
"en-GB": "/products/:productId",
sv: "/produkter/:productId",
},
});
const href = getPath(productDetailsPageContract, "sv", {
params: { productId: "sku-123" },
});
// /produkter/sku-123
Include exactly the configured locales (missing or extra locale keys fail type checking and contract creation) and use identical parameter names and optionality in each path. A unique localized path selects the request locale; shared paths need your application's locale policy. Translations explains locale resolution and dictionary loading.
Metadata and alternate representations
#Render Head from brix/islands/server in the server component to contribute document
metadata without maintaining a second HTML template:
import { Head } from "brix/islands/server";
export function ProductDetailsPage({ product }: ProductDetailsPageProps) {
return (
<>
<Head>
<title>{product.name}</title>
<meta name="description" content={`Details for ${product.name}`} />
</Head>
<main>
<h1>{product.name}</h1>
</main>
</>
);
}
The example replaces the earlier component and uses its props type. Keep metadata on the server; do not hydrate a component just to set its title.
For locale-keyed paths and dictionary loading, continue with translations. For an explicit semantic projection, add the contract's Markdown representation and the route's matching callback as shown in agent-readable Markdown.
Edge cache hints
#Pages are uncached unless they name a policy. Declare policy names once in defineBrixServer, for
example cachePolicies: ["publicPage"] as const, then select one on the route:
export const productDetailsPageRoute = createPageRoute(productDetailsPageContract, {
component: ProductDetailsPage,
cache: { policy: "publicPage", query: { bypass: ["preview"] } },
load: (c, { params }) => {
const product = products.get(params.productId);
if (!product) return c.notFound();
return { product };
},
});
cache: "publicPage" is the short form. The policy is a hint recorded in the production
brixManifest: Brix never stores page responses, and your edge decides what to cache with
decidePageCache from brix/edge. Each declared query field varies the cache key by default.
A cached page's query must be a z.object, a union of objects (keys vary by every branch's
fields), or an object or union followed by .transform(); a root z.preprocess() or another
schema throws at route creation because its wire field names are not finite.
query.bypass skips caching when a field is present, and query.shellIndependent excludes
reviewed fields from HTML-only shell keys. Both list wire field names: any union branch's field
is accepted, and a transformed query uses its input names, not its output names. Keep personalized pages uncached. See
fragments for the edge contract and
data caching for application data reuse, which is a separate concern.
Test and run
#brix test src/features/catalog/pages/productDetails/route.test.ts
brix dev
See testing for route-harness examples and islands for adding narrowly scoped interaction to SSR pages.