Compose and test fragments
After authoring a fragment, add composition in the trusted server or edge layer that fetches your Brix application. That layer owns origin routing, timeouts, cache storage, TTLs, and purging. Brix supplies the HTML protocol, deterministic route metadata, and pure cache decisions; it does not provision an edge or store responses.
Cache and compose at the edge
#Declare cache-policy names in defineBrixServer; a route's cache only emits an edge hint. An
omitted value or cache: false is uncached. Public cached fragments must not vary on undeclared
cookies, authorization, tenants, locale, or experiments. Use a private policy or complete
partitioning for personalized output.
Page-shell query policy is declared on the page route and stays independent of fragments:
forwarding campaign to a fragment does not prove that the shell ignores it. By default each
declared page query varies the shell key. shellIndependent excludes reviewed values from
HTML-only shell keys; bypass disables caching when a value is present; undeclared query always
bypasses caching. Pages that declare Markdown keep shellIndependent values in both representation
keys, because Markdown includes fragment semantics and HTML's automatic alternate URLs carry the
query, even in deferred shells. No second query policy is needed. See
caching for the distinction from application data caches.
Merge application manifests
#The built server entry exports brixManifest beside app. Manifest schema 2 lists every enabled
API, page, fragment, and Markdown-index route with its method, path, authentication flag, cache
hint, locale metadata, page representations and durable aliases, page query policy, and fragment
query names. A central edge merges the manifests of every application it routes, keyed by a
service name:
import { matchBrixEdgeRoute, mergeBrixManifests } from "brix/edge";
import { brixManifest as bookingManifest } from "@products/booking/app";
import { brixManifest as contentManifest } from "@products/content/app";
export const edgeManifest = mergeBrixManifests(
{ booking: bookingManifest, content: contentManifest },
{ cachePolicies: ["bookingWidget", "pageShell", "sharedChrome"] },
);
export function selectService(request: Request): string | undefined {
return matchBrixEdgeRoute(edgeManifest, request)?.service;
}
Merging fails on route, alias, and index collisions across services, on cache policies the edge
does not list in cachePolicies, and on a Markdown index whose auth differs from a represented
page it covers. Service and policy names start with a letter and use letters, digits, ., _,
or -. The edge helpers and manifest types are all imported from brix/edge.
matchBrixEdgeRoute follows Hono's non-strict pathname matching, with the same specificity as
origin registration: Unicode literals and unreserved percent escapes match their decoded forms, and
one trailing slash is ignored. Encoded reserved separators and percent data are not structural
delimiters. Encoded .md suffixes select Markdown at both origin and edge. Do not blanket-decode
paths before calling the helpers. HEAD matches the corresponding GET route. Pass a Request,
URL, or absolute URL string; a bare pathname such as url.pathname throws a TypeError because
cache keys include the request origin. Merged manifests are frozen, and Brix indexes each one once,
so lookup cost does not grow with every literal route.
Compose deferred shells
#For composition, the edge requests the shell with x-brix-fragments: defer. Brix replaces each
registered component instance with an inert template placeholder, and adds
Vary: x-brix-fragments to inline and deferred page responses that rendered a fragment. The
provider-neutral composeFragments helper resolves the placeholders concurrently and inserts their
HTML. Pass the live page URL so allowlisted page query can be forwarded.
The minimal composition flow, without response caching, is:
import { BRIX_FRAGMENT_MODE_DEFER, BRIX_FRAGMENT_MODE_HEADER, composeFragments } from "brix/server";
export async function composeOriginResponse(
request: Request,
fetchOrigin: (request: Request) => Promise<Response>,
): Promise<Response> {
const headers = new Headers(request.headers);
headers.set(BRIX_FRAGMENT_MODE_HEADER, BRIX_FRAGMENT_MODE_DEFER);
const shell = await fetchOrigin(new Request(request, { headers }));
return composeFragments(shell, {
pageUrl: request.url,
resolve: ({ source }) => {
const fragmentHeaders = new Headers(request.headers);
fragmentHeaders.delete(BRIX_FRAGMENT_MODE_HEADER);
return fetchOrigin(new Request(new URL(source, request.url), { headers: fragmentHeaders }));
},
});
}
Here fetchOrigin is your trusted routing function, not a fetch back to the public composer URL
(which would recurse). Forward credentials only to your own origin. Start with uncached composition,
then introduce storage after verifying personalized responses and CSP behavior.
resolve receives the fragment name, its same-origin source path, and the forwarded query
names, and returns a Response or an HTML string. The composer rejects malformed placeholders,
sources outside the fragment's own endpoint path, duplicate names, fragments containing
placeholders, non-2xx or non-HTML fragment responses, a missing pageUrl when a fragment forwards
query, and size or count overruns. Defaults are 20 fragments, 2,000,000 bytes for the shell, and
512,000 bytes per fragment; adjust maxFragments, maxPageBytes, and maxFragmentBytes only from
measured needs. Add provider-level origin timeouts.
The assembled response is always private, no-store, adds Vary: x-brix-fragments, drops the
shell's validators and length, and receives each fragment's Set-Cookie and Vary headers. Cache
the shell and fragments independently before composition, never the assembled result. Non-HTML
pages and HTML without placeholders return the original readable response.
A successful composition consumes the supplied page response: Brix reads the shell once and
cancels the unread original body, so do not read or return that response afterwards; clone it first
when it must also be cached. On terminal composition failure, Brix cancels both the supplied page
body and its internal read branch, and cancels rejected fragment response bodies. Cancellation is best-effort: delayed or
rejecting cleanup does not delay or replace the composition error. Pass unlocked response bodies;
release producer resources in the stream's cancel callback. Independently retained clones and
pending resolver operations remain the caller's responsibility; keep provider-level timeouts.
Cache admission contract
#Every cache decision is made twice with the same actual Request: once before lookup, and again
with the origin response before storage. A lookup use is provisional; store only when the
response decision also returns use. Never strip Vary or other headers to force admission.
For shells, set the defer header before lookup and pass that request to decidePageCache before
and after fetching the origin. Forward the mode unchanged and send the returned accept as the
origin's Accept, so negotiation matches the selected key. For fragments, call
decideFragmentCache the same way inside resolve:
import {
decideFragmentCache,
decidePageCache,
stripBrixPageRepresentationMarker,
type BrixEdgeManifest,
} from "brix/edge";
import { BRIX_FRAGMENT_MODE_DEFER, BRIX_FRAGMENT_MODE_HEADER, composeFragments } from "brix/server";
// Your provider's storage; each policy name maps to its own TTL and purge rules.
export interface EdgeCache {
match(policy: string, key: string): Promise<Response | undefined>;
put(policy: string, key: string, response: Response): Promise<void>;
}
export async function serveComposedPage(
request: Request,
manifest: BrixEdgeManifest,
cache: EdgeCache,
fetchOrigin: (request: Request) => Promise<Response>,
): Promise<Response> {
const shellHeaders = new Headers(request.headers);
shellHeaders.set(BRIX_FRAGMENT_MODE_HEADER, BRIX_FRAGMENT_MODE_DEFER);
const shellRequest = new Request(request, { headers: shellHeaders });
let shell: Response;
const lookup = decidePageCache(manifest, shellRequest);
if (lookup.cache === "bypass") {
shell = stripBrixPageRepresentationMarker(await fetchOrigin(shellRequest));
} else {
const cached = await cache.match(lookup.policy, lookup.key);
if (cached) {
shell = cached;
} else {
const originHeaders = new Headers(shellHeaders);
originHeaders.set("Accept", lookup.accept);
const response = await fetchOrigin(new Request(shellRequest, { headers: originHeaders }));
const admission = decidePageCache(manifest, shellRequest, response);
shell = stripBrixPageRepresentationMarker(response);
if (admission.cache === "use") {
await cache.put(admission.policy, admission.key, shell.clone());
}
}
}
return composeFragments(shell, {
pageUrl: request.url,
resolve: async ({ source }) => {
const fragmentHeaders = new Headers(request.headers);
fragmentHeaders.delete(BRIX_FRAGMENT_MODE_HEADER);
const fragmentRequest = new Request(new URL(source, request.url), {
headers: fragmentHeaders,
});
const fragmentLookup = decideFragmentCache(manifest, fragmentRequest);
if (fragmentLookup.cache === "bypass") return fetchOrigin(fragmentRequest);
const cached = await cache.match(fragmentLookup.policy, fragmentLookup.key);
if (cached) return cached;
const response = await fetchOrigin(fragmentRequest);
const admission = decideFragmentCache(manifest, fragmentRequest, response);
if (admission.cache === "use") {
await cache.put(admission.policy, admission.key, response.clone());
}
return response;
},
});
}
Cache keys are strings in the brix:3 namespace, built from the wire URL with only the query
values that partition the entry, sorted:
- inline HTML:
brix:3:html:inline:<origin><path?query> - deferred HTML:
brix:3:html:defer:<origin><path?query> - Markdown:
brix:3:markdown:<origin><path?query> - fragments:
brix:3:fragment:<origin><path?query>
The request origin (scheme and host) is always part of the key because rendered HTML carries
request-derived data such as the render-data baseUrl, so entries for different hosts never mix.
Keys keep the wire pathname, so equivalent spellings and a durable .md alias versus its
negotiated canonical URL remain separate entries. Custom keys must preserve the origin, mode,
representation, locale, and query partitions.
Page requests bypass (with a reason) when the route has no cache hint, is marked auth, or uses
opaque locale selection; when the request is not GET (including HEAD), carries
Authorization, sends an x-brix-fragments value other than exactly defer (reason
fragment-mode; an explicit inline also bypasses, and an absent header selects inline), has an
undeclared or bypass query, or accepts no available representation. Page responses are admitted
only when they are 2xx, carry the private representation marker and media type for the selected
representation, are not private or no-store, have no Set-Cookie, have no nonce-based CSP, and
vary on nothing except Accept, plus x-brix-fragments for HTML requested with exactly
x-brix-fragments: defer. Inline responses that rendered a fragment therefore stay uncached: their
body can depend on query values excluded from an HTML-only shell key. A URL or string cannot
describe composition mode, so it cannot admit fragment-varying HTML.
Fragment requests bypass when the route has no cache hint, is marked auth, the request is not
GET or carries Authorization, the query contains an undeclared key, or __brix_locale is
repeated or not one of the manifest's fragment locales. Fragment responses are admitted only when
they are 2xx text/html, are not private or no-store, and have no Set-Cookie and no Vary.
Brix already rejects shared cache policies on authenticated routes and marks their responses
private; the decisions enforce the same rule at the edge.
On cached HTML-only pages, render data omits cache.query.shellIndependent values from the
initial query string, matching the shell key; islands read the live browser URL after hydration.
Markdown indexes are never cached at the shared edge. Strip the private representation marker
with stripBrixPageRepresentationMarker before returning or storing any page response.
Deliver a fresh CSP
#The default origin Content Security Policy authorizes scripts with a per-response nonce, and page
admission rejects any response carrying one, because a stored nonce would be replayed to every
visitor. Markdown and plain-text responses run no scripts, so Brix sends them a nonce-free
policy with script-src 'none' and they remain admissible. To store HTML at a shared edge,
set security: { contentSecurityPolicy: false } in defineBrixServer only when the trusted edge
emits a fresh, complete CSP for every delivery. Brix then renders its bootstrap scripts with an
empty nonce attribute, so the edge policy must authorize them per response, for example by
writing one fresh nonce into both its CSP header and those attributes. Keep 'strict-dynamic' or
the asset origin so the bootstrap can still import island modules. See
security headers for the default directives.
Hydrate fragment islands
#Fragment endpoints can contain islands. They return scoped HTML with inert hydration metadata and no executable script; the assembled page's nonce-authorized bootstrap hydrates immediate, idle, and lazy roots in every fragment.
Independent fragment roots initialize concurrently, so a slow immediate island in one fragment does not block another fragment's controls. Nested roots retain ancestor-first initialization, and immediate modules within each root retain encounter order. Repeated initialization reuses in-flight root work. The generated bootstrap still waits for fragment initialization before starting page islands; there is no page-versus-fragment priority setting.
Because fragment metadata is ordinary markup, the bootstrap accepts it only from a JSON script
element (type="application/json" with the data-brix-fragment-hydration attribute) that is a
direct child of its data-brix-fragment root. It imports a fragment's island modules only when
every module URL resolves under the page application's asset prefix (the dev-server origin in
development), excluding the generated releases/<id>/ directory so independently cached fragments
from an earlier release still hydrate. Fragments with malformed metadata, or whose islands load
from another origin, another application's asset prefix, or a data: or blob: URL, are logged
and left unhydrated without blocking other fragments. This stops injected HTML from using the
nonce-authorized 'strict-dynamic' bootstrap to load arbitrary scripts. The module check cannot
tell a real root from raw HTML imitating one with an application module and its own props, so the
server also fails any page or fragment render whose raw HTML (dangerouslySetInnerHTML) contains
data-brix-fragment or data-brix-fragment-hydration attributes; see
island boundaries in raw HTML.
Localize fragment endpoints
#Deferred URLs carry the page's resolved locale in Brix's reserved __brix_locale query value.
Endpoint schemas cannot declare it. The endpoint resolves that locale before application
middleware runs, so server messages, component translations, and Content-Language agree; a
repeated value or one outside the configured locales returns 400. Manifests list each fragment's
finite locales so edge keys partition them, and a locale value without matching manifest metadata
bypasses caching instead of sharing output across locales.
Test transport and composition
#Use project-bound testFragment and testPage from #brix/test, and mockFragment from brix/test.
The following example assumes a booking page that renders the widget with hotelId: "hotel-1" and
declares the optional campaign query:
const endpoint = await testFragment(BookingWidgetFragment, {
params: { hotelId: "hotel-1" },
pageQuery: { campaign: "summer" },
});
const composed = await testPage(bookingPageRoute, {
query: { campaign: "summer" },
fragments: [BookingWidgetFragment],
});
const mocked = await testPage(bookingPageRoute, {
query: { campaign: "summer" },
fragments: [
mockFragment(
BookingWidgetFragment,
({ params, pageQuery }) => `${params.hotelId}:${pageQuery.campaign}`,
),
],
});
testFragment exercises validation and endpoint loading. Passing fragments to testPage sends
the real defer header, forwards page query, and runs production composition in process against
real fragment routes or typed mocks; without fragments the page renders inline. A mock sees only
public params and forwarded query, never server-loaded props. Test real routes for integration and
mocks for deterministic parent-page cases; missing registration, transport violations, and
endpoint failures fail the test. Fragment composition applies only to the HTML representation.
brix test src/features/chrome/components/siteHeader.fragment.test.ts
brix check
brix build
See testing for harness setup and Markdown representations for the explicit semantic boundary.