alepha@docs:~/framework/docs/guides/frontend$
cat 2-routing.md | pretty
10 min read
Last commit: Nov 29, 2026

#Routing

Alepha uses the $page primitive to define React routes, with support for data loading, code splitting, SSR, SSG, nested routing, and type-safe parameters.

#Setup

typescript
1import { $page } from "alepha/react/router";

Routes are defined as class properties. The class is registered with the Alepha instance in your entry files.

#Defining Pages

A complete example from a real Alepha application:

typescript
 1import { z } from "alepha"; 2import { $page } from "alepha/react/router"; 3import { $client } from "alepha/server/links"; 4  5import type { CountApi } from "./CountApi.ts"; 6  7export class AppRouter { 8  countApi = $client<CountApi>(); 9 10  home = $page({11    head: { title: "Home" },12    schema: {13      query: z.object({14        name: z.text({ default: "Alepha" }),15      }),16    },17    loader: async ({ query }) => {18      return {19        greeting: `Hello, ${query.name} SSR!`,20        count: await this.countApi.inc().then((result) => result.count),21      };22    },23    lazy: () => import("./Home.tsx"),24  });25 26  about = $page({27    head: { title: "About" },28    path: "/about",29    lazy: () => import("./About.tsx"),30  });31}

#Page Options

#name

The page's route name, used by router.push("home"), router.path("home") and useRouter<AppRouter>()'s type-safe names. Defaults to the class property key (home, about above) and must be unique.

#path

URL pattern with parameter support. A child page's path is appended to its parent's, so a page only declares its own segment. If omitted, it defaults to "": a root page answers on /, a child page on its parent's path (an index page).

typescript
1path: "/users/:id";2path: "/blog/:slug";

#schema

Type-safe URL parameters and query strings using Zod schemas.

typescript
1schema: {2  params: z.object({ id: z.integer() }),3  query: z.object({ tab: z.text().optional() }),4}

Parameters and query values are validated and typed in the loader and component props.

#loader

Data fetching function. Receives typed params and query, every prop returned by the parent layers' loaders, and the router state (url, name, head, meta). The returned object is passed to the component as props, and to the loaders of the child pages. In SSR, it runs on the server and its result is serialized into the HTML, so the browser does not run it again when it hydrates. During client navigation it runs in the browser: call the API through a $client, never a server service.

typescript
1loader: async ({ params, query }) => {2  const user = await this.userApi.getUser({ params: { id: params.id } });3  return { user };4};

When the URL changes, only the layers whose page, params or query changed re-run their loader; the others keep their props. A layer that re-runs forces every layer below it to re-run too, since their loaders received its props:

Flowchart diagramyes, and no layer above re-rannoyesnoNavigation to a new URLMatch the route: root layout to leafpageNext layer: same page, params andquery as before?Reuse its propsRun its use middleware, then itsloaderMerge the result into the propspassed downMore layers?Render the layers into nestedNestedViews

#component and lazy

Provide the React component to render. Use lazy for code splitting (recommended):

typescript
1// Code splitting (recommended)2lazy: () => import("./UserProfile.tsx")3 4// Direct component5component: ({ user }) => <div>{user.name}</div>

Lazy-loaded modules must use a default export.

A page with neither component nor lazy renders a bare <NestedView />: a pure layout layer, useful for grouping children under a path, a loader or a use guard without any markup of its own.

#head

Set document head tags (title, meta, etc.). Can be static or dynamic:

typescript
 1// Static 2head: { 3  title: "About Us"; 4} 5  6// Dynamic, based on loader data 7head: (props) => ({ 8  title: props.user.name, 9  description: `Profile of ${props.user.name}`,10});

A page's head is merged over the global $head() and over the heads of the layouts above it, by one rule on the server and in the browser: the tags a head declares for a key replace every tag the heads before it declared for that key. The key of a meta tag is its name or property plus its media, so a page's meta: [{ name: "robots", content: "noindex" }] replaces a global robots tag instead of sitting beside it, and two theme-color tags with different media queries stay two tags. One head may declare a key several times (two og:image, several article:tag), and all of them are kept, in order. Links accumulate, except the canonical: a page's own url or link: [{ rel: "canonical" }] replaces the one above it, and no canonical is filled in beside one you wrote.

A global titleSeparator chains the titles of every level, deepest first: with $head({ title: "App", titleSeparator: " | " }), a layout titled "Docs" and its child titled "Intro" give Intro | Docs | App. A page that sets only title also gives that title to an og:title or twitter:title that came from a title above it. One set on purpose, through og: { title }, twitter: { title } or a meta entry, is left as it is.

twitter:card is summary_large_image for a head with an image and summary for one without. A page that names no image keeps the card of the head above it, so a site that declares an image gets the large card on every page, not only on those repeating the image.

bodyAttributes belong to the page that sets them: a client navigation to a page without them removes them, as a full load would. For class, only the class names the head added are removed, so one set by another script (a theme's dark) stays.

A data block (any script whose type is not JavaScript) cannot close its <script> element with a value from a loader: a JSON block (application/json, application/ld+json, importmap, speculationrules) is written with < as a JSON escape, and any other gets a backslash inside </script, and inside a <!-- that a <script follows. An executable inline script is written as given.

typescript
1head: (props) => ({2  script: [3    { type: "application/ld+json", content: JSON.stringify(props.product) },4  ],5});

useHead() updates the head from a component. It takes the same fields, SEO fields included (description, image, url), and only adds or updates tags.

#Canonical URLs

Every page gets a <link rel="canonical">, plus og:url and twitter:url, without declaring anything. Set PUBLIC_URL and they are built from it and the page's matched route path:

txt
PUBLIC_URL=https://example.com   →   <link rel="canonical" href="https://example.com/docs/routing">

It is built from the route path, not the request URL, so ?utm_source=newsletter and a trailing slash never reach the tag - collapsing those duplicates is the entire job of a canonical, and one built from location.href would certify them instead.

Nothing is emitted when there is no PUBLIC_URL to build on, for wildcard and /404 routes, or when a layer errored - in each case there is no single URL the page could honestly name, and a relative canonical resolves against whichever host served it, which is exactly the ambiguity being removed.

To point a page somewhere else - a duplicate that should defer to the original - set url yourself:

typescript
1head: {2  url: "https://example.com/docs/routing";3}

Set it on a page, never in the global $head(): there it names the same URL for the whole site, and search engines read that as every page being a duplicate of that one. Alepha logs a warning if you do.

A canonical written as a link, link: [{ rel: "canonical", href }], wins the same way: nothing is filled in beside it, and when its href is absolute og:url and twitter:url take it too, so the three agree. It is inherited like any head tag, so one declared in a global head or on a layout is the canonical of every page under it, until a page declares its own url or canonical link: those pages then all name that one URL, with no warning for the link form.

#static

Pre-render the page at build time (SSG). On the server it goes through the automatic page cache like any other page, and is kept until the next deploy whether or not it has a loader.

typescript
 1// Simple static page 2static: true 3  4// With predefined entries 5static: { 6  entries: [ 7    { params: { slug: "hello-world" } }, 8    { params: { slug: "getting-started" } }, 9  ],10}

The prerender runs configure, never start. A static page is rendered at build time in an application that has been configured and not started, since starting it would listen on a port and connect to its databases inside the build. So a value a $hook({ on: "start" }) puts in the store is missing from the prerendered HTML, while the browser, which runs start before it hydrates, has it. If the page reads that value, the two trees differ and React reports a hydration error (#418) on every first load. Set anything a static page reads from the store on configure:

typescript
1class Themes {2  alepha = $inject(Alepha);3 4  register = $hook({5    on: "configure", // not "start": the prerender never runs it6    handler: () => this.alepha.store.set(uiThemeListAtom, THEMES),7  });8}

#ssr

Disable server-side rendering for the page component (@default true). With ssr: false the component renders client-side only (wrapped in <ClientOnly /> internally), but the loader still runs on the server - data fetching is unaffected. The value is decided at the leaf and inherited as a default by descendants: ssr: false on a parent acts as the default for its children, and a child can override with ssr: true.

A page behind a guard (use: [$secure()] on the page or on a layout above it) with no explicit ssr defaults to ssr: false: nobody who cannot run JavaScript gets past the guard, so painting its HTML on the server would cost CPU for no reader. An explicit ssr: true opts back in.

typescript
1ssr: false;

#Browser-only modules: *.client.tsx

ssr: false stops the server from rendering a page, not from bundling it: the build follows every import() it can see, so an editor or a chart library reached only from a client-rendered page still ships in the server bundle. Name the file that pulls it in *.client.tsx (or .client.ts) and it does not exist on the server. Every server-side build, and the server half of alepha dev, replaces it with a component that renders nothing, so nothing it imports is resolved there. The browser gets the real module.

tsx
1// Reports.client.tsx imports the chart library. The server never sees it.2reports = $page({3  path: "/reports",4  ssr: false,5  lazy: () => import("./components/Reports.client.tsx"),6});

Reach a .client module only from code the server never renders: a lazy page that is not server-rendered (ssr: false, or beneath a guarded layout such as $secure()), or a component inside <ClientOnly>. Rendered on the server anyway, it renders nothing and hydration reports the mismatch. Server code that imports one of its exports by name fails the build. Files under node_modules are never replaced.

#stream

Buffer the HTML instead of streaming it, so the page can choose its status code (@default true).

A page is streamed with an early <head> flush by default: the head leaves before the loader runs, which is what makes the first paint fast. The cost is that the HTTP status is committed by then, so a page whose existence depends on data cannot answer 404 - a missing product renders the error boundary with a 200, which a crawler indexes as a real page.

With stream: false the page renders to a string first and only then replies, so onServerResponse sees the finished render and can set reply.status.

typescript
 1product = $page({ 2  path: "/product/:slug", 3  stream: false, 4  loader: async ({ params }) => { 5    const product = await this.api.find(params.slug); 6    if (!product) throw new NotFoundError("No such product"); 7    return { product }; 8  }, 9  onServerResponse: ({ reply }) => {10    if (/* the loader found nothing */) reply.status = 404;11  },12});

Use it for the handful of routes that can legitimately not exist - a product, an article, a profile. Leave it alone everywhere else: buffering delays the first byte by the whole render.

#cache

The automatic page cache, for this page. A page that reads nothing about its visitor is cached with no option (until the next deploy without a loader, 60 seconds with one); cache: { ttl } sets another lifetime, cache: { invalidatedBy } names the writes that purge it, and cache: false opts out.

typescript
1cache: { ttl: [1, "hour"], invalidatedBy: [{ action: "productUpdate" }] }

#use

Attach middlewares to the page, such as a guard. A $cache here is refused: the page cache is automatic, and caching the whole document would store the visitor's private state with it.

typescript
1use: [$secure()];

Note. $secure on a page is a real guard. An anonymous visitor is refused at the router: with a login route declared, the result is a redirect to /login?redirect=<path>, and the loader's data never reaches the HTML; with no login route, the server answers 401. A signed-in visitor who lacks the permissions is not sent to the login page, which would loop: the server renders the not-found page with a 404. The two $secure variants refuse differently under the hood (the browser returns, the server throws), and the router normalises both - which also means a page's own errorHandler cannot catch the refusal, because on the server the middleware chain wraps the render.

Keep $secure on the endpoints underneath as well. Defense in depth: the API answers 401 whatever the interface does.

Two sign-in pages. Exactly one route can be called login, so an application serving two realms - a back office whose agents sign in with an identifier, a password and a realm, beside a public side asking for an email and a password - cannot say which door a denied page belongs to, and every refusal lands on whichever page holds the name. Set loginRoutesAtom to map a path prefix to a route name, first match wins:

typescript
1alepha.store.set(loginRoutesAtom, [2  { prefix: "/admin", route: "agent" },3  { prefix: "/", route: "signIn" },4]);

A prefix list rather than a resolver function, so the value is data: it validates, it serialises into the store, and it is set the same way on the server and in the browser. Unset - or set to a list nothing matches, or one naming a route that does not exist - the router resolves login exactly as it always did, so a single-realm application never touches this.

#can

UI-affordance predicate for the page's navigation entry - not security. Navigation surfaces (sidebar, breadcrumbs, command palette) consult it to hide or disable the entry; the router never does, and nothing returns a 403. For real access control, gate the page with use: [$secure({ permissions })], which is server-enforced. A page guarded that way with no can of its own gets one derived from the guard's permissions, so navigation surfaces hide it without the permissions being declared twice; an explicit can always wins.

typescript
1can: ({ has }) => has("admin"); // hide the nav entry2can: ({ has }) => has("admin") || "disabled"; // show it greyed out

#redirect

Redirect to another path when this page is matched - shorthand for throwing a Redirection in the loader. The redirect happens before any loader or component rendering.

typescript
1home = $page({2  path: "/",3  redirect: "/dashboard",4});

#nav

Navigation metadata - declares the page's presence in navigation surfaces (sidebar, breadcrumbs, command palette). A page without nav is route-only: reachable by URL but not listed. label, icon, description, and badge accept any ReactNode. Visibility is UI-only - an entry hides when nav.hidden is set, when nav.permission isn't fully granted, or when can() returns false.

typescript
1users = $page({2  path: "/users",3  nav: { label: "Users", icon: <Users /> },4  lazy: () => import("./pages/Users"),5});
Field Type Description
label ReactNode Entry label. Falls back to the page's label, then its head.title.
icon ReactNode Leading icon.
group string Section the entry belongs to: the sidebar group heading and the command-palette section.
order number Sort order within the group, ascending.
permission string | string[] Permissions required to see the entry, all of them, as in $secure({ permissions }). For OR or custom logic, can.
keywords string[] Extra command-palette search terms beyond the label.
description ReactNode Command-palette subtitle and sidebar tooltip.
badge ReactNode Trailing badge (an unread count, "New").
hidden boolean Keep the route out of navigation surfaces, as for a /users/:id detail page.

In @alepha/ui, useNavTree and NavShell build the sidebar from these fields; $pageNav declares nav and the route guard's permission in one place.

#props

Default props passed to the component; props returned by the loader override them.

typescript
1props: () => ({ pageSize: 25 });

#Nested Routing

Define parent-child relationships between pages using parent on the child or children on the parent. Parent pages render child content using the <NestedView /> component.

#Which option to use

The choice is not stylistic - it depends on who owns the child page:

  • You own the child (you wrote the $page and can edit it) → set parent on the child. The child declares its own place in the tree.
  • You don't own the child (it comes from another package or an injected router you can't modify) → add it to children on your parent. The parent adopts pages it doesn't control.

The second case is the reason children exists. When you $inject a router from another package, its $page definitions are frozen - you can't reach in and set parent on them. children is how you mount those external pages under one of your own layouts:

typescript
 1class AppRouter { 2  protected productRouter = $inject(ProductRouter); 3  4  layout = $page({ 5    path: "/app", 6    component: () => <Shell><NestedView /></Shell>, 7    children: () => [ 8      this.productRouter.catalogPage, 9      this.productRouter.checkoutPage,10    ],11  });12}

When you do own the child, prefer parent - it keeps parents free of forward references to their own descendants and reads top-down:

typescript
 1import { $page } from "alepha/react/router"; 2import { NestedView } from "alepha/react/router"; 3  4class AppRouter { 5  layout = $page({ 6    path: "/app", 7    component: () => ( 8      <div> 9        <nav>Sidebar</nav>10        <main>11          <NestedView />12        </main>13      </div>14    ),15  });16 17  dashboard = $page({18    path: "/dashboard",19    parent: this.layout,20    lazy: () => import("./Dashboard.tsx"),21  });22 23  settings = $page({24    path: "/settings",25    parent: this.layout,26    lazy: () => import("./Settings.tsx"),27  });28}

⚠️ Declare each edge from one side only. If page B already has parent: pageA, do not also list B in pageA.children. The link is already established; stating it on both sides creates a TypeScript circular dependency between the two class fields (each references the other before it is initialised).

<NestedView /> renders the matched child page. Its optional errorBoundary prop is false to drop the error boundary it wraps the child in, or (error, reset) => ReactNode for a custom fallback.

#When a page remounts

Each page in the matched stack is keyed by its own path, compiled from the params it matched: /epics/51 and /epics/50 are two keys, so navigating from one to the other remounts the epic page and everything below it. The layouts above it keep their key and their state. This is the Next.js App Router behaviour.

navigation page below the change layouts above
a param changes (/epics/51 to /50) remounted kept
only the query changes (?tab=history) kept, loader re-runs kept
router.invalidate() kept, loader re-runs kept

So a component may seed local state from its props, and a different record always starts fresh:

tsx
1const Epic = (props: { epic: Epic }) => {2  // Safe across `/epics/51` to `/epics/50`: the page remounts.3  const [draft, setDraft] = useState(props.epic.title);4  // ...5};

Two consequences to design around:

  • State that must survive a param change lives in the parent layout. A tree beside a document, a selected tab, a scroll position: put it in the layout that has no param (/folios, not /folios/:id) and let the child page read it, through a context scoped to that layout or an $atom.
  • invalidate() and a query change do not remount. The loader re-runs and hands the mounted page new props, so a useState(props.x) still holds the value it was seeded with. Read the prop directly where it must follow a reload.

A page with a :param in its path and no schema.params behaves the same way: its identity is compiled from the raw URL segment, so /users/1 to /users/2 remounts it and re-runs its loader.

#Ready-made surfaces from @alepha/ui

Two routers and one dialog ship whole surfaces you can mount instead of rebuilding:

Service Surface Extend with
AuthRouter /auth/{login,register,reset-password,verify-email} - (write your own to change the URLs)
AdminRouter /admin - users, sessions, keys, jobs, audits, … $pageAdmin
AccountDialog the account dialog - profile, security, sessions, API keys, connected apps $settingsSection

$pageAdmin is $pageNav already parented to the admin shell, so one call adds a page to its sidebar with no separate registration - the shell reads each page's own nav metadata. Put your pages in your own nav.group at order: 100 to 999, where they sort between the shell's built-in groups (the built-ins are parked at 1 and at 1000 and up), and gate with can: () => this.someApi.someAction.can() rather than permission alone, because a permission is self-declaring and stays granted over an API that was never mounted.

/admin is a root route with its own chrome: a NavShell sidebar derived from the route subtree, a topbar with a ⌘K search scoped to the shell, and the account menu. Do not adopt its layout into your own layout's children: it mounts its own Toaster, so every toast would show twice. Configure it through adminRouterOptionsAtom instead.

#The admin dashboard

/admin itself is a dashboard: a grid of tiles, each a number that opens the list it counts, filtered to the same number. Three ship with AdminRouter, each shown only when the server registers the action it reads:

Tile What it counts Opens
Users every account in the admin's realm; the chip compares sign-ups over the last 7 whole UTC days with the 7 before the Users list, with no stored filter applied
Connected distinct users who signed in or refreshed a session in the last 24 hours (API keys not included; it lags by up to an access token's lifetime) the Users list filtered to "last active: 24 h"
Failed audits audits of every type that failed, over the last 7 whole UTC days, against the 7 before; warning-coloured above a threshold (default 10) the audit log filtered to failed, every type, those days

Windows are whole UTC days because the audit log filters by day, and a tile must total what its list shows. Change the alert threshold with failedAuditsAlertThreshold in adminRouterOptionsAtom.

A link that carries no filter, like the Users tile's, would still get the filters the admin stored on that list last time. DataTable reads a reserved ?filters=none for that case: with filters.fromQuery set, the list opens with exactly the filters the link carries and none of the stored ones.

#Adding a tile

An application's tiles go in dashboardCards. AdminStatTile draws the built-in look: icon, label, an info tooltip saying what is counted, the number, a note, a delta chip and a warning tone, the whole card one link.

tsx
 1import { AdminStatTile, type AdminRouterOptions } from "@alepha/ui/admin"; 2import { useClient } from "alepha/react"; 3import { Package } from "lucide-react"; 4  5import type { OrderController } from "../api/OrderController.ts"; 6  7const OrdersTile = () => { 8  const orders = useClient<OrderController>(); 9  return (10    <AdminStatTile11      id="orders"12      label="Open orders"13      icon={<Package className="size-4" />}14      tooltip="Orders paid and not shipped yet."15      note={(loaded) => `${loaded.previous ?? 0} the week before`}16      href="/admin/orders?status=open"17      alert={(value) => value > 50}18      load={async () => ({19        value: await orders.countOrders({ query: { status: "open" } }),20        previous: await orders.countOrders({21          query: { status: "open", weeksAgo: 1 },22        }),23      })}24    />25  );26};27 28export const myAdminOptions: AdminRouterOptions = {29  dashboardCards: [30    {31      id: "orders",32      title: "Open orders",33      titleKey: "admin.orders.tile",34      render: () => <OrdersTile />,35    },36  ],37};

A card's fields:

  • id, unique across the built-in cards (users, connected, failed-audits) and yours: setting options that reuse one throws, at startup since every app sets its options before start;
  • title (required), the tile's name, which labels its region for screen readers; titleKey translates it;
  • order, ascending: the built-ins sit at 1000 and up, so a card with no order leads;
  • can, gated on the action the tile reads (() => this.api.countOrders.can()), never on a permission name, so the tile disappears with its module;
  • render, which owns the whole tile.

AdminStatTile's load returns the number, { value, previous } for a chip comparing the number with its previous value, or { value, delta: { current, previous, label } } for a chip comparing another number (the Users tile shows the total and compares sign-ups; label is the chip's tooltip). A failure renders "n/a" with the error in a tooltip, never a toast.

#Which tiles show

The tiles and their order are code: the built-in cards, then yours, sorted by order, each shown when its can passes. Every admin sees the same dashboard, and there is nothing to edit or store. To show your tiles only, drop the built-in ones:

typescript
1export const myAdminOptions: AdminRouterOptions = {2  builtinDashboardCards: false,3  dashboardCards: [/* ... */],4};

Above the tiles, the page greets the admin: "Hello", then their name, their username, or the part of their email before the @.

The account is not a route: AccountDialog declares a settings dialog (see below) named account, with five sections. The user menu opens it, and a link made outside the app opens it with ?account=<section>, as in /?account=sessions. Add a section with $settingsSection against AccountDialog.dialog, under the same order and can rules as an admin page; hide a built-in one or pass it props through accountDialogOptionsAtom:

typescript
1import { accountDialogOptionsAtom } from "@alepha/ui/account";2 3alepha.set(accountDialogOptionsAtom, {4  hide: ["connections"], // sections this application does not offer5  pages: { security: { deleteWarning: "Your projects are deleted too." } },6});

#Settings dialogs

Not every surface is a route. A settings dialog opens over the page the reader is on and drops them back there when it closes, the way the settings of a chat or mail client do. It is state, not routing: no route is registered, nothing is written to the URL, Back does not reopen it, and a reload closes it.

$settingsDialog declares one, $settingsSection adds a section to it from any class, and useSettingsDialog(name) opens and closes it:

typescript
 1import { $settingsDialog, $settingsSection } from "@alepha/ui/settings"; 2  3class PreferencesSettings { 4  dialog = $settingsDialog({ name: "preferences", title: "Preferences" }); 5  6  general = $settingsSection({ 7    dialog: this.dialog, 8    name: "general", 9    label: "General",10    group: "App",11    order: 1,12    lazy: () => import("./GeneralPreferences.tsx"),13  });14}

A section has no loader: its component fetches its own data with useQuery when it is shown. can hides a section, group and order place it in the nav, and groups sort by their smallest member. Reopening lands on the last section viewed; open("general") picks one.

The dialog closes by itself on any route change and when the user signs out. A link made outside the dialog (an email, a notification) opens it with ?<name>=<section>, as in /?preferences=general: read in the browser on load and on every client navigation, then removed from the URL. A signed-out visitor following it is sent to sign in first and lands in the dialog after.

#Error Handling

Use errorHandler to catch loader or rendering errors. It receives the error and the router state, and returns a ReactNode for a custom error page, a Redirection to redirect, null for the built-in error page, or undefined to let the error propagate. A page without a handler of its own uses its nearest parent's. Each handler in the chain runs at most once per error.

In production, an error the server caught reaches the browser's handler, on hydration, with its name, status and requestId only. The message and the data are kept for an HttpError below 500, which is said on purpose. For anything else (a 5xx, a plain Error, a library's error that carries a status) the message reads "Internal Server Error". This is stricter than an API response, which keeps the message of a library's error carrying a known 4xx status. Outside production the whole error is kept.

So an errorHandler that prints error.message for such an error shows the real message in the server's HTML and the constant one after hydration: a hydration mismatch, and a leak in the HTML. Render from error.name and error.status (isHttpError(error, 404)), and print error.message only for an HttpError you threw for the visitor.

typescript
 1import { NotFound, Redirection } from "alepha/react/router"; 2import { isHttpError } from "alepha/server"; 3  4errorHandler: (error, state) => { 5  if (isHttpError(error, 404)) { 6    return <NotFound />; 7  } 8  if (isHttpError(error, 401)) { 9    return new Redirection({ redirect: "/login" });10  }11}

The same handler also covers failures thrown around the render - a use: middleware such as a $rateLimit answering 429, or a server hook such as the not-ready guard that answers while the app is still booting. Those never run a loader, so there is no layer to fail; the router still resolves the nearest errorHandler and renders its result as a full HTML page.

When no handler applies, the built-in error page answers: the stack overlay in development, a plain card carrying the request id in production.

#HTML or JSON

The switch is the request's Accept header, and nothing else:

  • Accept: text/html: what a browser sends on a hard navigation - gets a rendered document.
  • Anything else, including the */* that fetch() defaults to, keeps the JSON error body. API clients are unaffected.

An error page is server-rendered and deliberately not hydrated: it ships no entry script, so the client cannot boot and re-render the very URL the server just refused. A custom error component is therefore static - hooks that read context (useRouter, useI18n) work, event handlers do not.

#Lifecycle Callbacks

  • onEnter: called when the user enters the page (browser only)
  • onLeave: called when the user leaves the page (browser only)

Neither fires for a page that stays on screen: router.invalidate(), router.reload() and a query change re-run the loaders without leaving or entering anything.

typescript
1onEnter: () => {2  analytics.trackPageView("/dashboard");3  window.scrollTo(0, 0);4};
  • onServerResponse(request): called on the server with the request and its reply. A streamed page calls it before the loader runs, once the head is ready to flush; a stream: false page calls it after the render, which is when it can still change reply.status (see stream). A page cache hit does not call it.

#Page methods

A $page is also an object you can call from server code:

  • page.render(options?) renders the page to HTML on the server and returns it with the router state. Meant for tests and build steps; it throws in the browser.
  • page.fetch(options?) requests the page from the running server over HTTP, at its full path with options.params and options.query filled in, and returns { html, response }; html is the content of the root element unless options.html is true.
  • page.invalidate(params?) purges the page from the page cache, every entry or those of one param set.

#Deferred Data

A promise at the top level of a loader's result is not awaited: the page paints at once, and reads the value with React's use() inside a <Suspense>.

tsx
1product = $page({2  path: "/products/:id",3  schema: { params: z.object({ id: z.text() }) },4  loader: async ({ params }) => ({5    product: await this.api.product(params), // awaited: in the first paint6    reviews: this.api.reviews(params), // deferred7  }),8  lazy: () => import("./Product.tsx"),9});
tsx
 1const Reviews = (props: { reviews: Promise<Review[]> }) => { 2  const reviews = use(props.reviews); 3  return <ReviewList reviews={reviews} />; 4}; 5  6const Product = (props: ProductProps) => ( 7  <main> 8    <ProductDetail product={props.product} /> 9    <Suspense fallback={<ReviewsSkeleton />}>10      <Reviews reviews={props.reviews} />11    </Suspense>12  </main>13);
  • On a server render the shell leaves first and each value streams into its boundary. In a build, hydration starts right after the shell, so the page answers clicks while a value is pending. alepha dev streams the same way but hydrates at the end of the document, since Vite's entry cannot run ahead of React Refresh.
  • On a client navigation the page renders at once and suspends.
  • Only top-level promises are deferred: one nested in an object is not looked at.
  • A rejection reaches the nearest errorHandler, and keeps name, message and status, so isHttpError works. In production the message of anything but an HttpError below 500 reads "Internal Server Error". Add a .catch in the loader for a value the page can live without.
  • A page with a deferred value is never stored in the page cache.
  • stream: false and a prerender await everything and write the settled values. So does a page with ssr: false, which has no HTML for a value to stream into.
  • head never sees a deferred value: it is filled before the render.

⚠️ The boundary goes under an element. React cannot flush the shell while a <Suspense> with no host element above it is pending, because it could still hold the <html>: the page would wait for the value, correctly but all at once. A <main> around it is enough. $page({ loading }) is such a boundary when nothing above the page renders an element.

⚠️ An atom written after the shell does not reach the browser. The payload leaves with the shell, so anything a deferred value should change on the client is the value itself.

#Link Prefetching

prefetch fetches a page's code before the click: the lazy chunk of the page and those of its layouts, never its loader data.

tsx
1<Link href="/invoices" prefetch="hover">Invoices</Link>2<Link href="/invoices" prefetch="visible">Invoices</Link>

hover waits 100 ms for intent. visible shares one IntersectionObserver, so keep it to a short list, never a table with hundreds of rows. The prop only sets data-prefetch, so a plain <a href="/invoices" data-prefetch="hover"> works too.

For a surface that is not a link, call the router:

tsx
1<DataTable2  onRowHover={(row) =>3    row && router.prefetch("invoice", { params: { id: row.id } })4  }5  onRowClick={(row) => router.push("invoice", { params: { id: row.id } })}6/>

#Loader data

prefetch: true on a $page declares its loader free of side effects, so a prefetch may run it too: hovering a tab starts its query, and the click paints at once.

tsx
1report = $page({2  path: "/reports/flow",3  prefetch: true,4  loader: async ({ query, signal }) => ({5    flow: await this.api.flow({ query }, { signal }),6  }),7  lazy: () => import("./Flow.tsx"),8});

The router runs the layers the target would not reuse, on a throwaway state, and keeps the result for the navigation that follows.

  • It runs only if every one of those layers opted in, or has no loader. Otherwise it does nothing, silently, and the link fetches its code alone: a parent loader that writes atoms must not run on a hover. Mark a loader only if it reads.
  • A use guard runs as on a navigation, and a denial or a failure is dropped: the click then does the work and shows the error.
  • A result lives 30 seconds, is used once, and is keyed by route, layer identity and decoded query. At most eight are kept. Nothing invalidates one, so a write within those 30 seconds is not reflected by it.
  • A click landing while the prefetch runs waits for it instead of sending the same requests again.
  • signal is aborted when the link leaves the page, and the result is dropped. A loader passes it on to cancel the request itself.

#Limits

At most four chunks load at once, each only once, and nothing loads under navigator.connection.saveData. A failed prefetch is ignored: an old chunk after a deploy never reloads the page under a hover. @alepha/ui's sidebar entries prefetch on hover unless a NavItem says prefetch: false.

#Modal Routes

overlay gives a page two presentations for one URL: an in-app navigation from a given page opens it over that page, and a reload or a shared link renders it in full.

tsx
 1class Router { 2  board = $page({ path: "/board", lazy: () => import("./Board.tsx") }); 3  4  card = $page({ 5    path: "/cards/:id", 6    loader: ({ params }) => this.api.card(params), 7    lazy: () => import("./CardPage.tsx"), 8    overlay: { 9      over: () => [this.board],10      lazy: () => import("./CardSheet.tsx"),11    },12  });13}

The overlay's component or lazy replaces the page's own and receives its loader props.

tsx
 1import { useOverlay } from "alepha/react/router"; 2  3const CardSheet = (props: { card: Card }) => { 4  const { close } = useOverlay(); 5  6  return ( 7    <Sheet open onOpenChange={(open) => !open && close()}> 8      <CardDetail card={props.card} /> 9    </Sheet>10  );11};
  • The page behind stays mounted and runs no loader. useRouterState() keeps describing it, so a layout reading name does not flip under the sheet: the overlay is in state.overlay, with its own name, params, url and layers.
  • It applies only when the committed page is in over and the overlay's parents are already on screen. From anywhere else it is a full page.
  • Back closes it and Forward reopens it. useOverlay().close() goes back through history. Neither scrolls the page behind.
  • A push from inside an overlay to a page that may open over the same background stays an overlay, so a link from one card to another replaces the sheet. Any other push leaves it.
  • onEnter and onLeave of the page behind do not fire when it opens, and the overlay's own fire when it opens and closes.
  • loading does not apply: the overlay opens once its loader is done. A loader that fails renders the page in full, where its errorHandler lands.

#Loading UI

loading is shown in the page's slot while its loader and its chunk load, with the layouts above it staying in place:

tsx
1invoices = $page({2  path: "/invoices",3  loading: () => <TableSkeleton />,4  loader: async () => ({ invoices: await this.api.list() }),5  lazy: () => import("./Invoices.tsx"),6});
  • It appears only if the navigation is still running after 200 ms (reactPageOptions.loadingDelay), so a fast page never flashes, and there is no minimum display time.
  • A page without one uses its nearest parent's, so a layout can declare one for all its children.
  • It only stands in for another page. A query change or router.invalidate keeps the page on screen, or a filter box would unmount itself on every keystroke.
  • It never shows on the first screen.
  • The URL does not move early: the address bar and the active sidebar entry stay on the old page until the new one is ready.
  • A navigation cancelled by going back restores the page, which remounts.
  • It is a plain component, never lazy: a skeleton that has to be fetched is not instant. It lands in the static graph, so keep it light.

It is also the page's <Suspense> fallback.

#View Transitions

viewTransition animates a page's slot when a navigation commits, through React's <ViewTransition>. The layouts above the slot do not move, and a browser without the API swaps instantly.

Values are CSS class names:

typescript
 1// One class, for the page arriving and the page leaving 2viewTransition: "fade" 3  4// Each direction apart. `update` is a change inside a page that stays, such as 5// a query change, and only runs when asked for. 6viewTransition: { 7  enter: "slide-in", 8  exit: "slide-out", 9  update: "pulse",10}11 12// From the target of the navigation13viewTransition: ({ url, meta }) =>14  url.pathname === "/checkout" ? { exit: "slide-left" } : undefined15 16// From where it comes from, and which way history moved17viewTransition: (to, { from, direction }) =>18  direction === "back" ? "slide-right" : "slide-left"

A function receives the target of the navigation, then what it knows of the navigation itself: from, the state that was on screen (absent on the first render), and direction, one of push, replace, back and forward. The last two are a move through history, the browser's buttons included.

The page leaving answers with exit, the page arriving with enter, and both play together. An exit no longer holds the navigation: it starts at the commit, with the new page ready. Style the classes with the view transition pseudo-elements:

css
1::view-transition-old(.fade) {2  animation: 200ms ease-in both fadeOut;3}4 5::view-transition-new(.fade) {6  animation: 200ms ease-out both fadeIn;7}

Going back and forward animates like any other navigation, so direction is what tells a slide which way to go.

A page with no viewTransition never animates. prefers-reduced-motion turns the option off, and so does a back gesture the browser already animated, or an iOS swipe back would play twice.

A navigation carries the target page's name as a transition type, and every view of it lands in one commit, so a shared element only needs a name, on the two pages it links:

tsx
1import { ViewTransition } from "react";2 3<ViewTransition name={`card-${card.id}`} share="morph">4  <h1>{card.title}</h1>5</ViewTransition>;

Views commit in a React transition, after react:transition:end. Code that needs the new page in the DOM listens to react:transition:committed.

#Router Hooks

#useRouter

Access the router for navigation. Typed against your registered routers (see below), or a type parameter for type-safe page name references.

typescript
 1import { useRouter } from "alepha/react/router"; 2  3const Nav = () => { 4  const router = useRouter<AppRouter>(); 5  6  return ( 7    <div> 8      <p>Current path: {router.pathname}</p> 9      <button onClick={() => router.push("/about")}>About</button>10      <button onClick={() => router.push("home")}>Home (by name)</button>11      <button onClick={() => router.back()}>Back</button>12      <button onClick={() => router.forward()}>Forward</button>13      <button onClick={() => router.reload()}>Reload</button>14    </div>15  );16}

Key methods and properties:

Method/Property Description
push(name, opts) / push(path, opts) Navigate to a page name (options: params, query, replace, meta, force) or to a path starting with / (no params).
back() Go back in history.
forward() Go forward in history.
reload() Reload the current page.
isActive(href, { startWith? }) Check if the given path is the current route (startWith matches on a segment boundary).
pathname Current pathname string.
query Current query parameters as Record<string, string>.
path(name, cfg) Resolve a page name to its URL path.
anchor(name, opts) / anchor(path) Returns { href, onClick } props for anchor elements, under the same two forms as push.
setQueryParams(record, { push? }) Update URL query parameters without navigation. Accepts a record or an updater (current) => next; replaces the history entry unless push: true. A key whose value is undefined or null is removed.
invalidate(props?) Re-run the current route's loaders without navigating (after a mutation the loader computes). A navigation in flight is not dropped: the invalidation runs once it has landed.
canGoBack Whether there is an in-app history entry to go back to.
state The current ReactRouterState (url, params, query, layers, ...).

push and anchor take one of two forms, told apart by type:

  • A page name, with that page's params: router.push("userProfile", { params: { id } }). On a typed router (useRouter<AppRouter>()) a misspelled name is a compile error, and params is typed from the page's schema.params and required when it has a required key. A page that declares schema.params gets exactly the params given; one that does not still inherits the current route's.
  • A path starting with /: router.push("/settings", { query: { tab: "security" } }). It honours query and replace; params belongs to a page name and is a type error here.

Nothing else is router navigation. A relative path, a bare ?query, an absolute https:// URL and a protocol-relative one (//host/path, /\host/path) are refused: changing only the query is setQueryParams, and leaving the app is an <a href> or window.location.assign. A dynamic path is typed `/${string}` where it is produced (the router exports it as RouterPath), not cast at the call.

A name no page has throws an AlephaError naming the closest ones, typed router or not. It used to navigate to the relative URL instead.

#Registering your routers

Register the app's routers once and useRouter() and <Link> are typed with no type argument:

typescript
1import type { AppRouter } from "./AppRouter.ts";2 3declare module "alepha/react/router" {4  interface Routers {5    app: AppRouter;6  }7}

Each entry is one router class, under a key of your choice. An app split into packages registers one per package (core: CoreRouter, work: WorkRouter), and the names useRouter() accepts are those of every entry together. A type argument still overrides the registration. With nothing registered, useRouter() stays untyped and takes any name.

⚠️ Code meant to run in any app, a shared package or a component library, writes useRouter<any>(): a bare useRouter() is typed against whichever app compiles it, so a library navigating by a dynamic name would stop compiling the day that app registers.

useRouter() does not re-render on navigation by itself. A component that renders from the current location reads it with useRouterState(), which subscribes to the router state and returns the ReactRouterState.

#useActive

Determine if a route is active and get anchor props for navigation links.

typescript
 1import { useActive } from "alepha/react/router"; 2  3interface NavLinkProps { 4  href: string; 5  label: string; 6} 7  8const NavLink = (props: NavLinkProps) => { 9  const { isActive, isPending, anchorProps } = useActive(props.href);10 11  return (12    <a {...anchorProps} className={isActive ? "active" : ""}>13      {isPending ? "Loading..." : props.label}14    </a>15  );16};

Accepts a path, a page name (resolved with router.path), or an options object:

typescript
1const { isActive } = useActive({ href: "/docs", startWith: true });2// isActive is true for /docs, /docs/intro, /docs/api, etc.

#useQueryParams

Manage typed query parameters with a schema.

typescript
 1import { useQueryParams } from "alepha/react/router"; 2import { z } from "alepha"; 3  4const SearchPage = () => { 5  const [params, setParams] = useQueryParams( 6    z.object({ 7      search: z.text().optional(), 8      page: z.integer().optional(), 9    }),10  );11 12  return (13    <input14      value={params.search ?? ""}15      onChange={(e) => setParams({ ...params, search: e.target.value })}16    />17  );18}

Options:

Option Type Default Description
key string "q" Param name for base64 format. Ignored by querystring.
format "base64" | "querystring" "base64" base64 packs the whole object into one opaque param (?q=…); querystring spreads each field as its own readable param (?search=…&page=…).
push boolean false true adds a history entry (pushState) so back returns to the previous value; false replaces the current entry (replaceState).

With format: "querystring", each schema field maps to its own URL param, and values are coerced back to their declared types on read (e.g. a z.integer() field reads ?page=2 as the number 2).

#Links and Anchor Interception

Plain <a href="/..."> anchors are intercepted automatically and routed through the SPA router - no <Link> wrapper required. This works inside React JSX as well as in raw HTML injected into the page (e.g. Markdown content rendered from a CMS).

html
1<a href="/about">About</a>

The interceptor bails out (and lets the browser handle the click natively) when any of the following apply:

  • the click uses a modifier key (meta, ctrl, shift, alt)
  • the mouse button isn't the primary one (middle/right click)
  • the anchor has target other than _self (e.g. target="_blank")
  • the anchor has a download attribute
  • the anchor has a data-no-router attribute (explicit opt-out)
  • the href uses a non-http(s) scheme (mailto:, tel:, data:, …)
  • the href points to a different origin
  • the href is hash-only (#section)
  • another listener already called event.preventDefault()

To force a hard navigation on a same-origin link, opt out per-anchor:

html
1<a href="/legacy" data-no-router>Legacy page</a>

To disable the global interceptor, set interceptAnchorClicks: false on the reactBrowserOptions atom (alepha.react.browser.options, exported from alepha/react/router). The same atom holds scrollRestoration: "auto" (the default) scrolls a new navigation to the top or to its #hash and restores the saved position on back and forward, "top" always jumps to the top, and "manual" leaves scrolling to you.

# component

<Link> is still available as a thin wrapper around <a> that wires the router via onClick directly:

typescript
1import { Link } from "alepha/react/router";2 3<>4  <Link href="/about">About</Link>5  <Link href="userProfile" params={{ id: "42" }}>6    Profile7  </Link>8</>;

href is a path or a page name, with params for a page name and query for either, as router.anchor takes them. Once your routers are registered, a name no page has is a compile error, and params is typed from the page's schema.params, required when it has a required key.

With the global interceptor enabled, <Link> is mostly a stylistic preference. Reach for it when you want explicit per-link control or intend to extend it with prefetching/active-state logic later.

#From server render to client navigation

A first visit is rendered on the server; every navigation after it runs in the browser. The loader results the server computed travel in the HTML, so hydration does not fetch them again:

Sequence diagramBrowserBrowserServerServerAPI actionsAPI actionsGET /users/42Match the route, run usemiddleware, look up the pagecacheFlush the head early (streamedpages)Run each layer's loaderStream the HTML, then the __ssrpayload (layers and atoms)Restore atoms, rebuild layers fromthe payload, hydrateRootClick on a link, router.pushRun the changed layers' loaders inthe browser, $client calls overHTTPRender, emit react:transition:endLoaders do not re-run on hydration

#Router Events

Route transitions emit events on the Alepha event system:

  • react:transition:begin: navigation started (includes previous and new state)
  • react:transition:success: navigation completed
  • react:transition:error: navigation failed
  • react:transition:end: always emitted after transition completes

A navigation also emits react:action:begin and react:action:end with type: "transition", so a global loading indicator covers it like any other action.

#Reference