Pages and routing

19 min read · Edit this page on GitHub

The page model everything else hangs off: how files become routes, how a page gets its data, how layouts nest, what <head> you control, how forms mutate, and what happens when something goes wrong.

Files are routes#

React components in pages/, routed by file name. There is no route configuration file to keep in sync:

File Route
pages/index.tsx /
pages/about.tsx /about
pages/tasks/index.tsx /tasks
pages/tasks/[id].tsx /tasks/:id
pages/orgs/[org]/members/[id].tsx /orgs/:org/members/:id

A [param] segment matches exactly one path segment; there are no catch-all or optional segments. Trailing slashes are ignored when matching, so /tasks/ and /tasks are the same route. A leading underscore means "not a route." Every file in pages/ whose basename starts with _ is excluded from the route table; three of them are then given a job instead — _layout.tsx wraps its directory, _404.tsx and _500.tsx become the error pages. Any other _-prefixed file is simply never served: pages/_helpers.tsx builds and ships nothing, silently. The rule is on the basename, not the directory, so an underscore on a folder hides nothing: pages/_components/Button.tsx has a plain basename and becomes a live route at /_components/Button. Put shared components in components/, outside pages/ entirely.

Loaders#

A page may export a loader that runs on the server before rendering. Whatever it returns becomes the component's props:

import type { LoaderContext } from "borgo-framework";
import type { Task } from "@/.borgo/api-types";

export async function loader({ params, api }: LoaderContext) {
  const { task } = await api("GET /api/tasks/{id}", { params: { id: params.id } });
  return { task };
}

export default function TaskDetail({ task }: { task: Task }) {
  return (
    <main>
      <h1>{task.title}</h1>
      <p>{task.body}</p>
    </main>
  );
}

The loader receives { request, params, api, apiUrl, session, locals, once }. params is Record<string, string> — every value is a string, decoded, exactly as it appeared in the URL. api is the typed client; apiUrl is the raw base URL for anything it does not model. session is the session Go verified, or null, and locals holds what api/middleware.go forwarded — both covered in middleware and authorization. once is for what a page's loader and its layouts' loaders both need: see asking once.

Loader code is stripped from client bundles at build time, so server-only imports, database handles and secrets used there never reach the browser. What the loader returns does: it is serialized into the page as JSON and readable by the visitor whether the component renders it or not, so return what the page shows, not the whole row.

The loader runs on the initial server render and on client-side navigations to that page — in the second case the client fetches its result as JSON rather than re-rendering the document. You do not write anything different for the two cases.

A loader can answer instead of returning props#

Return a Response and rendering is skipped. redirect(to, status = 303) makes that an auth guard:

import { ApiError, redirect, type LoaderContext } from "borgo-framework";

export async function loader({ api }: LoaderContext) {
  try {
    return { me: await api("GET /api/me") };
  } catch (error) {
    if (error instanceof ApiError && error.status === 401) return redirect("/login");
    throw error;
  }
}

This works identically on a full page load and on a client-side navigation: the runtime receives the redirect as data and follows it as a client navigation, so the guard cannot be bypassed by arriving through a link. It guards the loader only: a POST to the page runs its action with no loader in front of it. To guard every door of a page at once - document, props and action - use middleware.ts. See auth and sessions for the full pattern.

Layouts#

A _layout.tsx in any pages/ directory wraps every page below it. Layouts nest, outermost first, and receive children:

import type { ReactNode } from "react";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <div className="app">
      <header>
        <a href="/">Tasks</a>
        <a href="/about">About</a>
      </header>
      {children}
      <footer>built with borgo</footer>
    </div>
  );
}

pages/_layout.tsx wraps everything; pages/admin/_layout.tsx additionally wraps everything under /admin. Layouts live in the shared entry chunk rather than per-route chunks, which is why editing one triggers a full reload in dev instead of a hot update.

A layout with data#

A frame is often data: which workspace this is, who is signed in, what is in the sidebar. A layout may export a loader, with the same context as a page's and the same return values:

import type { LayoutProps, LoaderContext } from "borgo-framework";

export async function loader({ api, params }: LoaderContext) {
  const { tasks } = await api("GET /api/tasks");
  return { open: params.id, count: (tasks ?? []).length };
}

export default function TasksFrame({ children, open, count }: LayoutProps<typeof loader>) {
  return (
    <div>
      <aside>
        {count} tasks, #{open} open
      </aside>
      {children}
    </div>
  );
}

What the loader returns is the layout's props, beside children. The page under it does not receive them and does not have to ask for them.

  • No waterfall. The loaders of a route — every layout's and the page's — start together. A level of layout does not add a round trip, and a layout cannot hand its result to the page's loader: each asks for what it needs, and once keeps two that ask for the same thing from fetching it twice.
  • A layout can guard. A loader that returns a Response — redirect("/login") — answers for every page under it, and for their form actions: the layouts' loaders are heard before an action runs, so a request a layout refuses has changed nothing. The outermost layout speaks first and is not kept waiting by the ones under it. It decides what is answered, not what is requested meanwhile: the page's loader has started beside it, so data that must not even be requested has to be refused by middleware.ts or by the API, which is where authorization lives anyway.
  • It stays mounted. Between two pages under the same layout the layout is re-rendered with fresh data and not unmounted: its state, its scroll position and its subscriptions survive the navigation. The loader runs again on every navigation, with the page's.
  • Errors are the route's. A layout loader that throws fails the request as a page's does, and _500.tsx answers. The frame around _500.tsx may be the thing that failed, so there the rule is different: if a layout's loader throws or redirects while the error page is being rendered, the error page is rendered without its layouts rather than not at all.
  • Static export freezes data into files, a layout's as much as a page's: a page under a layout with a loader is exported only when the page says export const prerender = true.
  • Shared copies. A page with revalidate is rendered once for everyone, layouts included: what a layout's loader reads from session there is what a page's loader would, which is nothing.

The data travels with the page's props under the key borgo:layouts, which is why it is there in the document, in a client navigation and after a form action with nothing else to keep in step. Only the framework writes that key: a key of that name returned by a page's loader is dropped, and neither the page's component nor its head receives it. Each loader gets its own params object.

Asking once per request#

The loaders of a route run side by side and cannot hand each other anything, and they often need the same thing: the list the frame counts is the list the page shows. once(key, load) is on every loader's context. The first loader to ask under a key starts the work; whoever asks under the same key, while it runs or after, is given the same promise:

import type { LoaderContext } from "borgo-framework";

// in pages/tasks/_layout.tsx
export async function loader({ api, once }: LoaderContext) {
  const { tasks } = await once("tasks", () => api("GET /api/tasks"));
  return { count: (tasks ?? []).length };
}

The page under that layout writes the same line with the same key, and one request reaches the api, whichever of the two asked first.

  • A key is a name the loaders agree on, and nothing checks that two loaders mean the same thing by it: the second is handed what the first one's load returned, whatever its own load would have returned. Keep the key and the call together in one function both import.
  • It lasts one run of a route's loaders — one document, or one client navigation's props. Nothing is kept between requests, so it is not a cache, and one visitor's answer is never another's.
  • A failure reaches everyone who asked. If load throws or rejects, every loader awaiting that key gets the same rejection.
  • Only a loader has it. An action's context has none: an action is one function, with nobody to share with.

The page head#

Export head as an object, or as a function of the page's props and of what its layouts loaded:

import type { Head } from "borgo-framework";

export const head = {
  title: "Tasks",
  meta: [{ name: "description", content: "Everything still to do" }],
};
export const head = (props: { task: Task }): Head => ({
  title: `${props.task.title} · Tasks`,
  meta: [{ property: "og:title", content: props.task.title }],
});

During server rendering the title replaces the shell's <title> and the metas are injected into <head>. After hydration the runtime owns both, updating them on every client-side navigation and restoring the shell's title on a page that exports no head. Meta entries are attribute maps written through verbatim — no React, so no camelCase translation: the key you write is the attribute that lands, and the spelling is the HTML one ("http-equiv", not httpEquiv). Names that are not plain attribute names, and anything starting with on, are dropped silently on both the server and the client path.

A head function is handed a second argument, { layouts }: what the layouts around the page loaded, outermost first, with null for a layout that has no loader. A title that names the frame reads it there, and the page's own loader does not fetch the name again for the title alone:

import type { Head, HeadContext } from "borgo-framework";

export const head = (props: { title: string }, { layouts }: HeadContext): Head => ({
  // layouts[0] is what pages/_layout.tsx's loader returned
  title: `${props.title} · ${String(layouts[0]?.workspace ?? "Tasks")}`,
});

The entries are typed Record<string, unknown> | null, since head cannot know which layouts a page sits under: read them as you would read JSON. A head function with one parameter is called as before.

links are the <link> elements that say what a page is to other pages: its canonical address, the same page in another language, the next page of a list.

import type { Head } from "borgo-framework";

export const head = (props: { slug: string }): Head => ({
  title: "Pricing",
  links: [
    { rel: "canonical", href: `https://example.com/${props.slug}` },
    { rel: "alternate", hreflang: "it", href: `/it/${props.slug}` },
  ],
});

Only relations between documents are written: canonical, alternate, prev, next, author, license, help, me. A link that makes the browser fetch something — a stylesheet, a preload, an icon — belongs to index.html and to the build, and one given here is dropped, on the server and in the browser alike: head is often built from data, and data should not be able to ask a page to load a file. The href is a path of the site or an http(s) address.

lang is the language of this page, for a site in more than one language.

export const head = { title: "Compiti", lang: "it" };

On the server it replaces the lang attribute of the shell's <html>, or adds one. After a client navigation the runtime sets it on the document, and a page without a lang goes back to the one index.html was written with. The value has to be a language tag — letters, then groups of letters and digits after hyphens, it or en-GB or zh-Hant-TW — and anything else is ignored silently on both sides, since it is written into an attribute.

Streaming SSR#

Pages render through renderToReadableStream, so a <Suspense> boundary that suspends on the server sends the rest of the document immediately and streams the slow part in when it resolves:

import { Suspense, use } from "react";

function SlowPanel({ stats }: { stats: Promise<{ total: number }> }) {
  return <p>{use(stats).total} tasks all time</p>;
}

export default function Dashboard({ stats }: { stats: Promise<{ total: number }> }) {
  return (
    <main>
      <h1>Dashboard</h1>
      <Suspense fallback={<p className="fallback">Counting…</p>}>
        <SlowPanel stats={stats} />
      </Suspense>
    </main>
  );
}

The stream is pull-based: React is asked for the next chunk only when the client has room for it, so a slow connection throttles the render instead of letting a whole document pile up in server memory, and a client that goes away ends the render rather than paying for a page nobody will read.

Form actions#

A page may export an action; the render service runs it for POST requests to that page's URL:

import { CsrfField, redirect, type ActionContext } from "borgo-framework";

export async function action({ request, api }: ActionContext) {
  const form = await request.formData();
  const title = String(form.get("title") ?? "").trim();
  if (!title) return { error: "give the task a title" };
  await api("POST /api/tasks", { body: { title, body: String(form.get("body") ?? "") } });
  return redirect("/");
}

export default function Home({ actionData }: { actionData?: { error?: string } }) {
  return (
    <main>
      <form method="post">
        <CsrfField />
        <input name="title" placeholder="Title" />
        <button>Add</button>
      </form>
      {actionData?.error && <p className="error">{actionData.error}</p>}
    </main>
  );
}

What the action returns decides what happens next:

  • A Response is sent as-is. redirect(to) gives you post/redirect/get, which is what you want after a successful mutation.
  • Any other object re-renders the page with that object as the actionData prop, merged over the loader's props — the loader runs again first, so the page sees fresh data and the action's result. Validation errors belong here.

On hydrated pages the runtime enhances the form: the action runs over fetch and the page re-renders in place, keeping your scroll position. A redirect back to the same page refreshes it where you are; a redirect elsewhere becomes a client-side navigation. Without JavaScript — or on a hydrate = false page — the identical form falls back to the classic post cycle. Both paths are real, and both are tested.

One refusal is handled differently, because it happens before the action runs: a body over the size limit (BORGO_MAX_BODY, or a reverse proxy's own client_max_body_size) is answered 413, and on a hydrated page the runtime does not reload. Reloading would empty the form and throw away the one thing the server had said. Instead the page stays as it is, with everything typed still in it, and an overlay explains that nothing was saved and why — quoting the server's own text when it is prose rather than an HTML error page. This is not a dev-only overlay; it is the production behaviour of an enhanced form. Two other answers the action never produced, a 403 (stale CSRF token) and a 405 (a post to a page without an action), fall back to a native submit so the real error is the one you see.

Forms the runtime cannot re-render in place stay native: a GET form, a cross-origin target, a post to /api/.... To force the classic full-page submit on any form, add data-borgo-native:

<form method="post" action="/report.csv" data-borgo-native>
  <button>Download</button>
</form>;

<CsrfField /> is required inside every <form method="post"> — see CSRF protection for what it defends against. Required in production, that is: under borgo dev the check is off unless you set BORGO_CSRF=1, and it is skipped for a request carrying neither a session nor a csrf cookie. So a form that forgot the field works all the way through development and fails on the first real deploy. Add the field as you write the form, not when something 403s.

The same is true one level down of a browser call that mutates through /api/*: those echo the token in an X-CSRF-Token header rather than a field, and apiFetch from borgo-framework is the fetch that attaches it. Loaders and actions are unaffected — their api client calls the api's internal listener, and the header check guards the public port, not that listener.

One limit worth stating: an action that returns its own HTML document (rather than props or a redirect) is swapped into the page by the runtime, and because that reuses the current browsing context, inline scripts in that document are blocked by the page's existing Content-Security-Policy — in production, where that policy is strict; under borgo dev it carries 'unsafe-inline' and they run — and the page's hydration does not re-run. It is the right behavior for the error documents this path actually serves; if you need to send a custom HTML page from an action, redirect to a route that renders it instead.

Hydration control#

A page controls how much JavaScript it ships:

export const hydrate = false;      // no page bundle at all
export const hydrate = "visible";  // hydrate when the marked section scrolls into view

hydrate = false pages are pure server-rendered HTML; individual interactive pieces can still be <Island> components. See client navigation and hydration.

Cached pages#

A page that is the same for every visitor can say so, and stop rendering per request. Two things decide whether it really is cached: the copy is rendered as nobody - no session, no cookies - so a loader that reads session serves everyone the logged-out page; and a page middleware.ts can reach is never cached, so a matcher-less middleware.ts turns caching off for every page:

import type { LoaderContext } from "borgo-framework";

export const revalidate = 60;      // seconds a copy stays fresh
export const tags = ["tasks"];     // the data this page depends on

export async function loader({ api }: LoaderContext) {
  const { tasks } = await api("GET /api/tasks");
  return { count: (tasks ?? []).length };
}

export default function Summary({ count }: { count: number }) {
  return <p>{count} tasks right now</p>;
}

In production the first request renders the page as nobody: a plain GET carrying only Accept and User-Agent of what the visitor sent - no cookies, no Authorization, no verified session, no address of the visitor who triggered it, none of the negotiation a render could personalise on, and no other header a loader could read and bake into everybody's copy. The copy is cached and shared under the scheme and host that were asked, the path as written in its one spelling, and the query. Within the window every request is served from memory; past it the stale copy is served immediately while one background render replaces it, however many requests arrive at once. revalidate = "manual" never goes stale by clock: the copy lives until the data drops it.

Dropping it is the api's side of the contract. The moment a Go handler writes the data a page depends on, it names the tag — borgo.RevalidateTag("tasks") — and every page that declared it re-renders on its next request. borgo.Revalidate("/path") drops one page instead (its query variants with it, and every host that holds a copy of it; a trailing * drops a prefix). Both are local calls: the cache lives in the process your handler runs in, so an invalidation is a function call and not a round trip. It is also per instance — two borgo processes behind a load balancer each hold their own copies.

The shared property holds by construction, not by trust in your loader: a copy is refused — and the page served fresh per request, with one log line saying why — if the response was not a 200, set a cookie under any spelling, declared a Vary on anything but Accept-Encoding (a render saying its copy is not universal), or carries per-request bytes such as a <CsrfField /> token. That last check is the same one borgo export runs; the one residue a live server handles rather than refuses is the CSP nonce, which every replay re-mints. Responses carry X-Borgo-Cache: miss | hit | stale | bypass so you can watch all of this from curl.

In development every request renders fresh — the cache would fight the reload the dev channel just asked for. borgo export skips a revalidate page by name: a frozen file would honour neither the clock nor an invalidation, so the page asked for a server. Cached copies also survive a restart: they persist under .borgo/cache/html, keyed to the build that rendered them - each borgo build is a new key, so a source change served without one keeps the old copies. Performance has the mechanism end to end; the tasks example's /news page and its api/tasks.go handlers are the working pair.

Error pages#

  • pages/_404.tsx renders unmatched routes with status 404.
  • pages/_500.tsx renders server errors in production with status 500, without leaking the error.

Both go through the normal layout chain, and both may have loaders. In development an SSR error renders as a readable overlay instead of _500, and the client runtime surfaces uncaught errors and unhandled rejections in the browser. If _500 itself throws, the response degrades to a plain text 500 rather than a loop.

On the Go side, borgo.Handle panics with an actionable message on a malformed or duplicate pattern rather than failing silently at request time, and a handler that panics answers a JSON 500 instead of dropping the connection.

A page that throws in the browser#

_500.tsx answers for the server. In the browser there is no request to answer: a component that throws while rendering — after a click, on data a client navigation brought — used to take the whole tree with it, because React unmounts a root when nothing caught the error, and the visitor was left with an empty page. Since 1.1 every page is rendered inside a boundary. What it catches stays inside the page: the layouts around it stay in place, with their state and their links.

What is shown in place of the page is the page's to say, with an ErrorBoundary export:

export function ErrorBoundary({ error, reset }: { error: unknown; reset: () => void }) {
  return (
    <main role="alert">
      <h1>The board could not be shown</h1>
      <p>{error instanceof Error ? error.message : "Something failed."}</p>
      <button type="button" onClick={reset}>
        Try again
      </button>
    </main>
  );
}

export default function Board() {
  return <main>{/* ... */}</main>;
}

reset renders the page again, and so does going anywhere: a page that failed is tried afresh on the next navigation, not kept failed for the life of the tab. A page without the export gets borgo's own notice — a heading, This page stopped working, a line saying that what was typed elsewhere is untouched, and a button that reloads.

  • It acts only in the browser. On the server the same boundary is in the tree, so that both sides render one shape, and it catches nothing: a page that throws there is _500.tsx's, as before.
  • It catches rendering. An error thrown in an event handler or in a promise nobody awaited never reaches a React boundary, here or anywhere.
  • It wraps the page, not the layouts. A layout that throws is outside it.
  • A page with hydrate = false renders nothing in the browser, so there is nothing to catch.

Reporting errors#

Two functions hand what failed to whatever collects errors. Neither changes what the visitor sees or what is logged.

import { onClientError, onServerError } from "borgo-framework";
import type { ReactNode } from "react";

// report stands for your collector's client
const report = (error: unknown, where: string) => console.error(where, error);

onClientError((error) => report(error, location.pathname));
onServerError((error, { request }) => report(error, request ? new URL(request.url).pathname : "render"));

export default function RootLayout({ children }: { children: ReactNode }) {
  return <div className="app">{children}</div>;
}

onClientError is told of what React meets in the browser on a hydrated page: a page that threw and was caught by its boundary, an error no boundary caught, and one React recovered from by itself, such as a hydration mismatch. The second argument is what React reported alongside the error, the component stack included. onServerError is told of what fails while a page is rendered on the server: a page or a loader that threw, a stream that failed after its first byte; the request is there when the failure belongs to one. The log line and the 500 stay as they were.

Call each once, at the top of a module both sides load — the root layout is the usual place. Each keeps one handler, and a second call replaces the first. On the server onClientError's handler is never called, and in the browser onServerError's is a function nobody calls. A handler that throws is ignored: a reporter must not become the error it was told about. For a production stack to be readable, build with source maps.