defineRoute
Every field a route’s .data.ts may declare — placement, cache policy, budgets, streaming, regions — and what each one decides.
A route’s .data.ts default-exports defineRoute({…}). It is read at build time, so everything here becomes part of the generated plan rather than a branch taken per request — and everything here is checked against what the compiler inferred from the fragments it places. A declaration that contradicts a derivation loses, at build time, with the read that caused it named.
There is deliberately no cache key. Keys are derived from what a fragment was seen to read, and a declaration that could state one could disagree with the code.
Everything below is optional, and the useful default for most of it is silence: a route with no cache gets the class its fragments’ reads imply, a route with no stream anywhere lowers to in-order delivery and ships no filler script, and a page whose fragments read nothing becomes a file at build time without being asked.
import { defineRoute } from '@weftjs/core'
import { loadCart, loadRecommendations } from '../lib/cart.ts'
export default defineRoute({
head: { title: 'Cart' },
layoutValues: { heading: 'Your cart' },
// Checked against the strictest class anything on this page implies.
cache: { class: 'private' },
slots: {
// The route's own file. `body` is never given a `fragment`.
body: { load: loadCart, live: true },
// A later wave: it reads what `body` loaded, so the scheduler waits for it.
recs: {
fragment: 'cart/recs',
needs: ['body'],
load: loadRecommendations,
stream: { prio: 2 },
cache: { class: 'public', ttl: '5m', tags: ['recs'] },
budget: { cpu: '120ms', onExceed: 'degrade' },
placeholder: 'Loading recommendations…',
},
// A fragment that may render on another deployment. Where is the deployment's to say.
promo: {
fragment: 'cart/promo',
region: { remote: true, fallback: 'cart/promo-empty', optional: true },
},
},
})What a .data.ts default-exports.
Read at build time, so every field here becomes part of the generated plan rather than a branch taken per request — and every field is validated against what the compiler inferred.
| Field | Type | Required |
|---|---|---|
layout | string | optional |
head | HeadDeclaration | ((params: Record<string, string>) => HeadDeclaration) | optional |
layoutValues | Record<string, unknown> | ((params: Record<string, string>) => Record<string, unknown>) | optional |
load | RouteLoad | optional |
cache | CacheDeclaration | optional |
document | CacheDeclaration | optional |
stream | boolean | { prio?: number } | optional |
incremental | boolean | optional |
speculate | boolean | 'profile' | optional |
live | boolean | optional |
placeholder | string | optional |
executor | string | optional |
budget | BudgetDeclaration | optional |
budgetFor | BudgetFor | optional |
refresh | string | number | optional |
form | { prefer?: WireForm; fallback?: WireForm } | optional |
guard | (ctx: EnvelopeContext) => boolean | Promise<boolean> | optional |
redirect | string | optional |
status | number | optional |
slots | Record<string, SlotDeclaration> | optional |
maxConcurrency | number | optional |
order | 'in-order' | 'out-of-order' | ((params: Record<string, string>) => 'in-order' | 'out-of-order') | optional |
etag | boolean | optional |
static | false | optional |
notStaticBecause | string | optional |
params | Record<string, readonly string[]> | optional |
expose | string[] | optional |
exposes | string[] | optional |
Read from packages/weft/src/route.ts · RouteModule
layoutoptional
Which document wraps this page: app/layouts/<name>.tsx. Without one it is app/layout.tsx.
// app/layouts/wide.tsx wraps this page instead of app/layout.tsx.
layout: 'wide'headoptional
The title, the description and any other meta tag, as a value or a function of the params.
Never a function of the request: a head that varied per request would vary the document, whose cache key is derived from what its fragments read.
head: (params) => ({
title: `${params.slug} — Blog`,
description: 'One post.',
meta: { 'og:type': 'article' },
})layoutValuesoptional
Extra values for the layout's own holes, beyond the six the framework always supplies. Declaring them here is what makes the unfilled-hole check possible: a hole nothing supplies fails the build.
// The layout leaves a `heading` hole the framework knows nothing about.
layoutValues: (params) => ({ heading: params.category ?? 'Everything' })loadoptional
The body slot's values.
load: async (ctx, params) => ({ post: await ctx.services.posts.get(params.slug) })cacheoptional
The body slot's cache policy. Every other slot declares its own. See CacheDeclaration.
cache: { class: 'public', ttl: '5m', tags: ['posts'] }documentoptional
What the document response advertises. Checked against the strictest class on the page.
// What the response advertises, checked against the strictest class on the page.
document: { class: 'public', ttl: '1m', swr: '10m' }streamoptional
The body slot's delivery. false buffers, which derives in-order delivery for the page.
stream: { prio: 1 }incrementaloptional
The body slot's incremental re-render. See SlotDeclaration.incremental.
incremental: truespeculateoptional
Re-render this page's body after a response rather than on a reader's request. See SlotDeclaration.speculate.
// Warm it whenever its entry is in the last fifth of its life.
speculate: trueliveoptional
The body slot is refreshable over the channel. See SlotDeclaration.live.
live: trueplaceholderoptional
Rendered while the body is degraded. Without one a degraded body is empty, which is honest.
placeholder: 'Loading your cart…'executoroptional
Where the body renders. See SlotDeclaration.executor.
executor: 'pool:heavy'budgetoptional
What the body may spend, and what happens when it does not fit. See BudgetDeclaration.
budget: { cpu: '120ms', js: '8kb', onExceed: 'placeholder' }budgetForoptional
Overrides the body budget's cpu ceiling and exceed policy for this request. See BudgetFor.
// A page whose subject *is* the budget: move it and watch the exceed policy.
budgetFor: ({ query }) => ({ cpu: query.get('cpu') ?? '120ms', onExceed: 'degrade' })refreshoptional
Re-render the body on a clock while a reader is on the page. See SlotDeclaration.refresh.
refresh: '30s'formoptional
Which encoding the body's updates would rather use. See SlotDeclaration.form.
form: { prefer: 'delta', fallback: 'html' }| Field | Type | Default |
|---|---|---|
prefer? | WireForm | optional |
fallback? | WireForm | optional |
guardoptional
Runs in phase A, where the envelope is still open — so a redirect here is a real redirect rather than a mid-stream apology. See spec/kernel/lifecycle.md.
// Phase A, so this redirect is a real redirect rather than a mid-stream apology.
guard: async (ctx) => Boolean(await ctx.user())redirectoptional
Where a refusing guard sends the request. Without one it refuses with status.
redirect: '/sign-in'statusoptional
What a refusing guard answers with when there is no redirect. Defaults to 403. A real status is available only because phase A runs before the first body byte promises a 200.
status: 404slotsoptional
The layout's other slot holes, filled per route. body is this file and cannot be redeclared.
slots: {
body: { load: loadCart },
aside: { fragment: 'cart/summary', needs: ['body'] },
}maxConcurrencyoptional
Ceiling on concurrent slot renders for this page, overriding the deployment's own. For the one page whose fan-out is different from the rest of the application.
maxConcurrency: 2orderoptional
Delivery order, when it has to be a control rather than a consequence.
Normally derived: a plan whose slots all buffer expresses no interest in arrival order. Stated as a function of the params, because a query string the router cannot see would not do.
// The exception is a page whose *subject* is the difference between the two orders.
order: (params) => (params.mode === 'stream' ? 'out-of-order' : 'in-order')etagoptional
Answer a conditional request for this page: a strong ETag over the bytes, and a 304 when the reader already holds them.
Declared rather than derived, because an entity tag has to be in the envelope and so costs streaming entirely. Declaring it on a route that streams is E_ETAG_STREAMS at build time — the trade is worth taking on a page that buffers anyway, and never worth taking silently. See spec/kernel/cache.md.
// Only on a page whose slots all buffer: declaring it on one that streams is E_ETAG_STREAMS.
etag: truestaticoptional
false when this page must not be resolved at build time, and why.
An opt-*out*, because the L0 derivations are right nearly always. What they cannot catch is a loader reading a query key the probe did not invent — see spec/kernel/static.md.
static: false,
notStaticBecause: 'the head reads ?src, which the invariance probe cannot invent'notStaticBecauseoptional
Why this page is not a file. Required with static: false: a refusal with no reason is noise.
notStaticBecause: 'renders a per-request nonce into the CSP'paramsoptional
The values each of this route's parameters can take, when they are a set the application knows. This is what makes a parameterised page a file.
Nothing infers the set, and every parameter in the pattern has to be here or the route is refused with the missing ones named. See spec/kernel/static.md.
// This is what makes a parameterised page a file: two values, two URLs, two files.
params: { category: ['books', 'music'] }exposeoptional
Extra value names to send to the browser, beyond the ones a client-owned derived expression was seen to read. Everything not listed stays on the server.
Not exposes below: this decides which of a *slot's* values reach that slot's own client code.
// `qty * unitPrice` recomputed in the browser already sends `unitPrice`.
// This is for a value the browser needs for a reason the template cannot show.
expose: ['currency']exposesoptional
Shell values this page offers its regions, by name.
The only channel between a shell and the regions inside it, declared rather than discovered so that a region's consumes can be checked against it. A name here has to be a value the shell actually renders with. See spec/kernel/composition.md.
// The only channel between a shell and the regions inside it.
// A region declaring `consumes: ['locale']` on a page that exposes nothing is a build error.
exposes: ['locale', 'cartCount']One entry per hole the layout leaves. body is the route’s own file and is never given a fragment; every other name has to be a hole the document actually leaves, or the build refuses it with the holes it does leave listed.
| Field | Type | Required |
|---|---|---|
fragment | string | optional |
load | RouteLoad | optional |
html | string | ((ctx: RenderContext, params: Record<string, string>) => string | Promise<string>) | optional |
cache | CacheDeclaration | optional |
stream | boolean | { prio?: number } | optional |
incremental | boolean | optional |
speculate | boolean | 'profile' | optional |
executor | string | optional |
budget | BudgetDeclaration | optional |
budgetFor | BudgetFor | optional |
placeholder | string | optional |
refresh | string | number | optional |
form | { prefer?: WireForm; fallback?: WireForm } | optional |
needs | string[] | optional |
live | boolean | optional |
region | RegionDeclaration | optional |
Read from packages/weft/src/route.ts · SlotDeclaration
fragmentoptional
Which fragment renders it, by name under app/fragments/. Omitted for the body slot, which is the route's own file, and for a slot with html.
// app/fragments/cart/items.tsx
fragment: 'cart/items'loadoptional
Where this slot's values come from. Runs in phase B, after the envelope is sealed, so it cannot redirect and cannot set a header — that is guard's job.
load: (ctx, params) => ({ items: ctx.services.cart.of(params.id) })htmloptional
Markup rather than content — a control panel, a readout. Goes through raw(), and says so.
// Markup rather than content: a control panel, a readout. Goes through raw().
html: (ctx, params) => `<p class="hint">${params.id}</p>`cacheoptional
How long this region may be held and what invalidates it. See CacheDeclaration.
cache: { class: 'public', ttl: '1h', tags: ['catalogue'], consistency: 'strong' }streamoptional
Streamed with an optional priority. false buffers, which derives in-order delivery.
// A lower number arrives first. `false` buffers.
stream: { prio: 2 }incrementaloptional
Re-render through this slot's own memo, so only the holes whose values moved cost bytes. Worth it for a slot whose template is large and whose values mostly are not. See spec/kernel/surgical.md.
// A large template whose values mostly do not move: only the changed holes cost bytes.
incremental: truespeculateoptional
Re-render this slot after a response rather than on a reader's request. true warms it in the last fifth of an entry's life; 'profile' leaves the decision to a measurement.
Speculation about a clock, not about a reader — see spec/kernel/locus.md.
speculate: 'profile'executoroptional
Where this slot renders, by the name it is bound under in weft.config.ts.
inline and client are always available; anything else has to be in executors there, or the build fails with E_UNKNOWN_EXECUTOR and the slot named.
executor: 'svc:search'budgetoptional
What this slot may spend, and what happens when it does not fit. See BudgetDeclaration.
budget: { cpu: '80ms', onExceed: 'fallback' }budgetForoptional
Overrides budget's cpu ceiling and exceed policy for this request. See BudgetFor.
budgetFor: ({ query }) => ({ cpu: `${query.get('ms') ?? 80}ms` })placeholderoptional
Rendered while the slot is degraded. Without one a degraded slot is empty, which is honest.
placeholder: '<div class="skeleton" aria-hidden="true"></div>'refreshoptional
Re-render this slot on a clock while a reader is on the page. '30s', or milliseconds. Only does anything on a live slot: the refresh travels over the channel.
// Only does anything on a `live` slot: the refresh travels over the channel.
live: true,
refresh: '15s'formoptional
Which encoding this slot's updates would rather use, and what to fall back to.
A preference and not a choice — the form is negotiated per request, and every form of a fragment produces identical bytes. See spec/kernel/surgical.md.
form: { prefer: 'patch', fallback: 'html' }| Field | Type | Default |
|---|---|---|
prefer? | WireForm | optional |
fallback? | WireForm | optional |
needsoptional
Data this slot depends on, by slot name. A slot merely nested inside another does not declare it.
// A data dependency, so the scheduler puts this slot in a later wave.
needs: ['items']liveoptional
Refreshable over the channel: the slot is registered with the hub under a key derived from the route and the tags, so an intent writing one of those tags produces a STALE frame for exactly the connections showing it.
// An intent writing one of this slot's tags produces a STALE frame
// for exactly the connections showing it.
live: true,
cache: { class: 'public', ttl: '1m', tags: ['cart'] }regionoptional
This slot is a region: a fragment that may render on another deployment.
region: { remote: true, fallback: 'search/empty', consumes: ['locale'] }What a slot declares about being held, checked against what its fragment was seen to read. The same shape fills document, which is what the response itself advertises.
| Field | Type | Required |
|---|---|---|
class | PolicyClass | required |
ttl | string | number | optional |
swr | string | number | optional |
tags | string[] | optional |
consistency | 'eventual' | 'strong' | optional |
Read from packages/weft/src/route.ts · CacheDeclaration
classrequired
public or private. Checked against the class this slot's reads derive, never trusted.
class: 'private'ttloptional
How long an entry may be served. '5m', '1h', or milliseconds. Required wherever a fragment read the clock.
ttl: '5m' // or 300_000swroptional
Stale-while-revalidate: how long past the TTL an entry may answer while it refreshes. Same spellings as ttl.
swr: '1h'tagsoptional
What invalidates this. An intent that declares one of these tags drops this entry when it runs.
tags: ['cart', 'prices']consistencyoptional
What the bound store can honestly claim. Defaults to eventual; a slot needing strong is refused on a store that cannot promise it.
consistency: 'strong'What a slot may spend, in the spellings a person writes: '120ms', '8kb'.
Read from packages/weft/src/route.ts · BudgetDeclaration
cpuoptional
CPU this slot may spend before the exceed policy applies. '120ms', or milliseconds.
cpu: '120ms'jsoptional
JavaScript this slot may add to the page. '8kb', or bytes. A ceiling on what was *built*, which is why budgetFor cannot override it.
js: '8kb'growoptional
How much the ceiling above may grow before the build fails. A growth cap is a diff.
grow: '512b'onExceedoptional
What happens when the slot does not fit: stale, client, fallback, placeholder or fail.
onExceed: 'placeholder'A slot that is a fragment living somewhere else. It declares that there is a boundary and what the shell expects across it — never where, because a shell naming the tier would make rolling that region a redeploy of every shell that names it. Where is regions in the config.
Read from packages/weft/src/route.ts · RegionDeclaration
remoteoptional
It crosses a deployment boundary, and what the shell expects to find. true describes nothing, so the region reads opaque.
// `true` describes nothing, which is legal and expensive: an undescribed
// region reads `opaque`, so the document containing it is uncacheable.
remote: { serves: 'search results', form: 'html' }fallbackoptional
A fragment rendered in this region's place when it fails, by name under app/fragments/.
fallback: 'search/unavailable'optionaloptional
Failure is invisible: an empty hole and nobody paged.
optional: truecspoptional
Directives this region needs. Merged into the document's one policy, and refused on conflict.
csp: { 'script-src': ["'self'", 'https://maps.example.com'] }consumesoptional
Shell signals this region reads. Checked against defineRoute({ exposes }).
// Checked against the shell's own `exposes`.
consumes: ['locale']criticaloptional
Ours, and in the first flush. A remote region may not be critical: the flush cannot wait.
// Ours, and in the first flush. A remote region may not be critical.
critical: trueWhat goes in the document head for this route. A function of the params, never of the request — a head that varied per request would vary the document’s cache key.
| Field | Type | Required |
|---|---|---|
title | string | optional |
description | string | optional |
meta | Record<string, string> | optional |
Read from packages/weft/src/route.ts · HeadDeclaration
titleoptional
The document's <title>.
title: 'Your cart'descriptionoptional
The <meta name="description">, and what a share card says.
description: 'What you are about to buy.'metaoptional
Any other <meta name=… content=…> pair. og: and twitter: names are written as given.
meta: { 'og:image': '/card.png', robots: 'noindex' }