brust 2.0.0-alpha.66
Guide / Loaders and params

Loaders and params

A loader is an async function on a route. It runs in a Bun worker for each request, and what it returns becomes the props of the route's components.

Write a loader

lib/loaders.ts
import { type LoaderCtx, notFound } from '@brust/core/routes'
import { fetchPokemon } from './pokeapi'

export async function detailLoader({ params }: LoaderCtx<{ name: string }>) {
  const p = await fetchPokemon(params.name)
  if (!p) return notFound({ name: params.name })
  return { name: p.name, types: p.types, art: p.art }
}

// routes.tsx
{ path: '/pokemon/{name}', Component: DetailPage, loader: detailLoader }

What a loader gets

@brust/core/routes
interface LoaderCtx<P> {
  params: P        // decoded route params
  path: string     // the request path
  req: {
    method: string
    url: string
    headers: Record<string, string>
    cookies: Record<string, string>
    search: Record<string, string>   // query, url-decoded, + is a space
  }
  res: {
    headers: Headers   // response headers, one object for the whole chain
  }
}

How the data reaches components

The page component receives the loader's object as its props:

pages/DetailPage.tsx
export default function DetailPage({ name, types, art }) {
  return (
    <article>
      <img src={art} alt={name} />
      <h1>{name}</h1>
      <p>{types.join(' / ')}</p>
    </article>
  )
}

When layouts have loaders too, they run first, root to leaf, and their results are merged into one object that every component in the chain receives. A child's key wins over a parent's. A loader that returns nothing adds nothing.

Note

The merge is flat, so name keys with care. On this site the layout loader returns version for the header; a page loader returning its own version would replace it on that page. Group page data under one key (this page uses demo).

Try a lookup

On a brust server, a loader like the one below reads ?pokemon= from req.search and looks the name up in the site's Pokémon module, and the page is rendered again with the new data. This site is a static export, so the demo runs the same lookup in your browser and rewrites the address.

/docs/loaders?pokemon=pikachuLoaderDemo · native

Pikachu#025

Pikachu

electric

Found in lib/pokemon.ts.

pages/docs/Loaders.tsx
// pages/docs/Loaders.tsx on a brust server (this static site runs the lookup in the browser)
export async function loadersLoader({ req }: LoaderCtx): Promise<LoadersData> {
  const query = (req.search.pokemon ?? 'pikachu').trim().toLowerCase().slice(0, 30)
  const p = byName(query) // lib/pokemon.ts
  return { toc, blocks, demo: { query, found: p !== undefined, card: p ? cardOf(p) : unknownCard(query) } }
}

For a route param, open /demo/pokemon/eevee: its loader reads params.name, and on a brust server an unknown name such as /demo/pokemon/agumon returns notFound(). This site ships as static files and the route's cache rule reads the query string, so the static build leaves it out (ssg: false); run the docs locally with bun run dev to open it.

Not found, error pages, redirect, errors

lib/loaders.ts
import { httpError, notFound, redirect, renderStatus } from '@brust/core/routes'

return notFound({ name })            // 404, renders this route's page with the data
return renderStatus(403, { name })   // the same at any 400-599 status
return redirect('/pokedex', 308)     // Location header, nothing rendered (default 302)
httpError(429, 'slow down')          // throw-only: any 400-599 status and a body
  • The first verdict stops the chain: loaders below it do not run.
  • notFound(data) renders the route's own page with status 404, its data merged over the parent loaders' data.
  • renderStatus(status, data) does the same at any status from 400 to 599: a 403 page for a visitor without access, a 451, a 503 maintenance page. The layouts, the loaders' data and their response headers are all there, and the page is never stored in the cache. notFound(data) is renderStatus(404, data). Another status throws when the loader calls it: a 3xx is redirect(), a 200 is the data itself.
  • Use httpError() instead when the answer is a body and not a page: an API-style JSON error, a plain-text 429. It renders no template and no layout.
  • httpError takes a string body (sent as text/plain; charset=utf-8) or an object (sent as application/json; charset=utf-8). The third argument can name another type, { contentType }, and add headers; a server-owned name there (see Response headers) is dropped with a warning, in brust dev too. A thrown Error is a 500, with the message in the server log.
  • A response that carries Set-Cookie is never stored in the page cache.

Response headers

res.headers is a standard Headers for the response. Use it to set cookies, turn off caching, or send a policy such as Content-Security-Policy or Referrer-Policy for a page:

lib/loaders.ts
import { redirect } from '@brust/core/routes'

// a layout: every page under it is never cached
export function accountLoader({ res }: LoaderCtx) {
  res.headers.set('Cache-Control', 'no-store')
  return {}
}

export async function logoutLoader({ req, res }: LoaderCtx) {
  await endSession(req.cookies.sid)
  res.headers.append('Set-Cookie', 'sid=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax')
  res.headers.append('Set-Cookie', 'theme=; Max-Age=0; Path=/')
  return redirect('/login', 303)   // both cookies go with the redirect
}
  • There is one object per request, shared by every loader in the chain. Loaders run root to leaf, so a layout can set a header for every page under it and a page can add to it. set replaces a value, andappend adds one, so two Set-Cookie stay two.
  • The headers go on whatever the chain answers: the page, notFound(), redirect() and httpError(). A thrown Error is a plain 500 without them.
  • Content-Type, Content-Length, Transfer-Encoding, Connection and Location belong to the server (a redirect's target comes from redirect()). Setting one throws in brust dev, and in production it is dropped with a warning that names it.
  • The page cache never stores a response with Set-Cookie, a Cache-Control with no-store or private, or a Vary that names any field other than Accept-Encoding (Vary: *, Cookie and Accept-Language included): the cache key holds no request header, so such a page would be served to everyone.
  • Cache-Control: no-store also keeps the page out of the browser's navigation cache (see Navigation).
  • A static build (--target static) writes files, which carry no headers: they are dropped, and the build warns with ssg-headers, naming them.