Skip to content

Private previewMost of the architecture is written. First public release in 2027.

Routing

Every file under app/pages/ is a route. The component samples in the guides use React; the other libraries use the same names, and Adapters lists what differs.

Files and routes

File in app/pages/PathNotes
index.tsx/
about.tsx/about
blog/index.tsx/blog
blog/[slug].tsx/blog/:slugrequired param
users/[[id]].tsx/users/:id?optional param
docs/[...path].tsx/docs/**:pathcatch-all, one or more segments
files/[[...path]].tsx/files/**:path?optional catch-all, zero or more
shop/[category]-[id].tsx/shop/:category-:idseveral params in one segment
items/[id=integer].tsx/items/:ida param that passes the matcher app/params/integer.ts
(marketing)/pricing.tsx/pricinga (group) folder adds nothing to the path
[...slug].tsxevery unmatched paththe app's own 404 page, for a request that prefers HTML; it answers 200 unless the page throws createError({ status: 404 }). A request that does not prefer HTML and matches no page gets a JSON 404

Files and folders that start with _ or . are ignored, except the folder files named in Route conventions; *.test.*, *.spec.* and *.d.ts are ignored too. Two files that resolve to the same path are a build error that names both.

A page reads its params with useRoute():

tsx
import { useRoute } from "@hamur/adapter-react";

export default function BlogPost() {
  const { params } = useRoute();
  return <h1>Post {params.slug}</h1>;
}

A catch-all param is a string[]. [...path] never matches an empty path; use [[...path]] for that.

tsx
import { useRoute } from "@hamur/adapter-react";

export default function DocsPage() {
  const { params } = useRoute();
  const segments = params.path as string[];
  return <p>{segments.join(" / ")}</p>;
}

The best match wins, compared segment by segment: a static segment, then a segment that mixes text and params, a required param, an optional param, a catch-all, and last an optional catch-all. A param is decoded with decodeURIComponent; a malformed escape answers 400. Matching is case-sensitive and ignores one trailing slash. Set app.trailingSlash to "redirect" and a page request for /about/ is answered with a 308 to /about, keeping the query. This holds in the built server and in hamur dev. A path that matches no page stays 404, and server routes are not redirected. Set it to "always" and a page request for /about is answered with a 308 to /about/ (query and baseURL kept), every Link renders and every navigation pushes the slash form, and canonical links end in /; file-like paths (/logo.png), server routes and /_hamur/ are left alone. The static presets write the rule into _redirects for each page without params. Set it to "strict" and /about/ is a 404 for a page (the root / excepted); server routes are not touched. The default is "ignore". With app.caseSensitive: false a page matches in any case and a page request for /About is answered with a 301 to /about, before any slash redirect; a client navigation pushes the lower-case path.

Param matchers

[id=integer] takes the page only when the matcher integer accepts the value; any other value goes on to the next route that fits. A matcher is a file app/params/<name>.ts that exports match:

ts
// app/params/integer.ts
export function match(param: string): boolean {
  return /^\d+$/.test(param);
}

With items/[id=integer].tsx beside items/[slug].tsx, /items/12 is the first page and /items/abc the second. The =matcher part goes on any param form: [[id=integer]], [...path=segments], [[...path=segments]] and a param inside a mixed segment ([sku=integer]-[color]). A catch-all's matcher gets its segments joined by /; an absent optional param is not checked. At one place a param with a matcher comes before the same param without one, and two matchers are tried in name order. The route name and params ignore the matcher: the page above is items-id with params.id.

The matchers ship to the browser, so a client navigation picks the same page as the server. match must return a boolean, or the request fails with app/params/integer.ts: match must return a boolean (got object). A page that names a matcher with no file fails the build with Unknown param matcher "integer" in app/pages/items/[id=integer].tsx (no app/params/integer.ts). Handler routes are plain paths and take no matcher.

Escapes

Some characters cannot be written in a file name, or would mean something else there. In a page or folder name, [x+HH] (two hex digits) and [u+HHHH] (four) stand for that character, and [.] for a dot. All three are plain text: never a param, a suffix, a group, a slot or a route-syntax character.

File in app/pages/Path
smileys/[x+3a]-[x+29].tsx/smileys/:-)
foo[.]error.tsx/foo.error, a page and not the route boundary of foo
[x+40]sidebar/index.tsx/@sidebar, a path and not a slot
[[lang]]-docs.tsx/docs and /en-docs: one optional param beside literal text

The route name keeps the escape without its brackets (x+3a), so no route name holds a :. [x+2f] (a /), a control character and a surrogate are build errors, and so is [x+3]: Bad escape "[x+3]" in app/pages/a[x+3].tsx: write [x+HH] with two hex digits or [u+HHHH] with four. A segment holds one optional param and no other param; [[a]]-[[b]] fails with A segment holds one optional param and no other param: app/pages/[[a]]-[[b]].tsx.

Route conventions

A few names in app/pages/ are not pages. Each comes in two forms, a suffix of a page file and a file in a folder. In the samples on this page, the path under routing/ is the path under app/pages/.

FileWhat it isCovers
dash.error.tsx, dash/_error.tsxroute boundarydash/_error.tsx the routes in dash/ and below, not dash itself; dash.error.tsx also dash
shop.not-found.tsx, shop/_not-found.tsxnot-found componentthe same
slow.pending.tsx, dash/_pending.tsxpending componentthe same
_not-found.tsx (in app/pages/)root not-found componentevery route, and a URL no page matches
t/_template.tsxroute templatethe routes of t/, see Remounting a page
admin/_meta.tsfolder configevery route in admin/ and below
(app).tsx beside (app)/pathless group layoutthe routes in (app)/
@team/index.tsx, @team/default.tsxslotthe page beside the @team folder
(..)photo/[id].tsx in a slotintercepting routesee Intercepting routes

A folder file never covers the folder's own parent page dash.tsx; the suffix form does. For each route and each kind, the scanner takes the nearest covering file, walking up from the page: its own suffix file, its folder's _<kind>, the parent page's suffix file, the parent folder's, and so on up to app/pages/_<kind>. A (group) folder and an @slot folder count as folders in this walk. Each kind takes an extension of your library, as a page does; _meta.ts takes .ts, .mts, .js or .mjs.

Build errors catch the usual slips, each naming the file:

SlipMessage
a suffix file without its pageapp/pages/foo.error.tsx is the route boundary of app/pages/foo, which is not a page; add the page, or serve /foo.error from app/pages/foo[.]error.tsx
two files of one kindTwo route boundaries for app/pages/dash: app/pages/dash.error.tsx and app/pages/dash.error.jsx
a typo within one letterapp/pages/dash/_eror.tsx looks like a misspelled app/pages/dash/_error.tsx: rename it
a Next.js nameapp/pages/dash/_loading.tsx: a folder's pending component is app/pages/dash/_pending.tsx
a Remix nameapp/pages/admin/_layout.tsx: a folder's layout is its parent page app/pages/admin.tsx, or app/pages/(admin).tsx for a group
_meta with a wrong extensionapp/pages/admin/_meta.tsx: a folder config ends in .ts, .mts, .js or .mjs

Route boundaries and not-found components

A route boundary shows an error of one route inside the page, so the layout and the parent pages above it stay on screen. It catches an error thrown or answered by the route's load (its parent() chain included), by route middleware named in meta.middleware or a folder config, by meta.params and meta.validate, by a search schema, and by the render of the route's component. With dash.error.tsx and a failing dash/broken, the error renders inside dash, which keeps its nav; a failing dash itself is replaced, inside the layout.

tsx
import { clearError, useError } from "@hamur/adapter-react";

export default function DashError() {
  const error = useError();
  return (
    <section>
      <h2>{`Dash failed: ${error?.status}`}</h2>
      <button type="button" onClick={() => void clearError()}>
        Try again
      </button>
    </section>
  );
}

The component reads the error with useError() and leaves with clearError(), which clears the error and runs the current URL again, or clearError({ redirect }). The answer has the error's status. The page:error hook runs before the boundary renders, as for the error page.

A not-found component is the same for a 404: the one covering the failing route wins over a route boundary at any level, and a 404 with no not-found component takes the nearest route boundary. Throw notFound() in a load to reach it (Errors).

tsx
import { Link, useError } from "@hamur/adapter-react";

export default function PageNotFound() {
  const error = useError();
  return (
    <main>
      <h1>{error?.message ?? "Not found"}</h1>
      <Link to="/">Back home</Link>
    </main>
  );
}

What a boundary never catches is shown by the error page, unchanged: a redirect, false or abortNavigation() from middleware, a createError({ fatal: true }), an error of a layout's load or of the layout or the root component, a malformed path (400), and an error thrown while a boundary itself renders. When several loads fail, the outermost failing route wins and the others are logged.

app/pages/_not-found.<ext> also answers a URL that no page matches, with status 404. By default it renders inside the root and the default layout. With app.notFoundMode: "fuzzy" the deepest parent page whose path is a prefix of the URL renders with its layout and parents, and the not-found component covering its children renders in its Outlet; if there is no such page, the root one answers. See Errors.

Pending components

A pending component shows while a client navigation is still loading after 1000 ms. It renders at the first page entry of the target that is not on screen, and the entries above it stay mounted with their data. The first load, a shallow navigation, refresh() and the server never show one, and a navigation that finishes sooner never does either. The component reads useNavigation() (state is "loading", to the target); useRoute() is still the page on screen and useData() is null.

tsx
import { useNavigation } from "@hamur/adapter-react";

export default function DashPending() {
  const navigation = useNavigation();
  return <p>{`Loading ${navigation.to ?? ""}`}</p>;
}

A newer navigation replaces the pending component. A navigation that ends without a page, because a guard or abortNavigation() cancelled it, puts the page on screen back.

Folder config

app/pages/admin/_meta.ts exports meta, as a page does, and it applies to every route in admin/ and below. Use it for a guard or a layout that a whole folder shares.

ts
import type { PageMeta } from "hamur/app";

export const meta = { middleware: "auth", layout: "admin" } satisfies PageMeta;

A page's key wins over a folder's, and a deeper folder's over an outer one's. middleware is not replaced: a folder config's middleware runs before the middleware of the routes it covers, so a page with middleware: "log" below this folder runs auth and then log. A folder config holds run-time keys only; a build key in it fails with app/pages/admin/_meta.ts sets meta.path, which is read per page; a folder config holds run-time keys only. export default fails with app/pages/admin/_meta.ts has a default export; a folder config exports meta: export const meta = { … } satisfies PageMeta, and a file with no meta with app/pages/admin/_meta.ts exports no meta. It works in (group) folders and slots.

Pathless group layouts

(app).tsx beside a folder (app)/ is the layout of the routes in that folder. It adds nothing to the path: (app)/settings.tsx is /settings. It renders Outlet, takes meta (its middleware runs as a parent page's does), (app).load.ts for its data (read with useData() in it), and the suffix files above.

tsx
import { Outlet } from "@hamur/adapter-react";

export default function AppShell() {
  return (
    <div>
      <header>My app</header>
      <Outlet />
    </div>
  );
}

The group is never matched alone, and it is not a route you can navigate to by name. Below a parent page it keeps the parent's name: admin/(tools).tsx and admin/(tools)/logs.tsx are /admin/logs, with the names admin, admin-(tools) and admin-logs. useRoute().groups lists the group folders of the page file without parentheses, outermost first. A (group) folder without a (group).tsx is only a folder. A (group).tsx without its folder fails with app/pages/(app).tsx is the layout of app/pages/(app)/, which does not exist.

Slots

A folder @team beside a page dash.tsx is a slot of that page. The page renders it where it puts <Outlet name="team" />, next to the main Outlet. A folder name must match /^@[a-z][a-z0-9-]*$/; any other @ folder (@[user]) is a path segment.

tsx
import { Outlet } from "@hamur/adapter-react";

export default function Dash() {
  return (
    <section>
      <main>
        <Outlet />
      </main>
      <aside>
        <Outlet name="team" />
      </aside>
    </section>
  );
}
tsx
export default function TeamIndex() {
  return <p>Your team</p>;
}

For a URL, each slot is matched against the same URL as the main chain, after it and never instead of it. dash/@team/index.tsx renders at /dash, and dash/@team/settings.tsx at /dash/settings. The slot's route names are dash@team and dash@team-settings. A slot page's load runs beside the main chain's, in parallel, and useData() inside the slot reads its own route's data; useRoute() in a slot is the main route.

When the URL has no page in the slot, default.<ext> renders. A slot with no default renders nothing, and hamur dev logs [hamur] slot @team of app/pages/dash.tsx has no page for /dash/settings and no default.<ext>; it renders nothing. On a client navigation, a slot with no page for the new URL keeps its last chain while the owner stays on screen.

tsx
export default function TeamDefault() {
  return <p>Pick a team</p>;
}

Slots replace Nuxt's named views. A file dash/@sidebar.tsx fails the build: app/pages/dash/@sidebar.tsx: a named view is a slot; move it to app/pages/dash/@sidebar/index.tsx (its page) or app/pages/dash/@sidebar/default.tsx (every URL). Other slot mistakes are build errors too: a slot with no owner page (app/pages/dash/@team: a slot belongs to the page app/pages/dash.<ext>, which does not exist), a slot inside a slot, and a slot page whose URL no main page serves.

Intercepting routes

A page under a (.), (..) or (...) folder inside a slot intercepts a path when a client navigation comes from the page that owns the slot. The prefix says where the path starts: (.) at the owner's path, (..) one segment above it, (...) at /. Groups and slots are no segments here.

tsx
import { Link, Outlet } from "@hamur/adapter-react";

export default function Feed() {
  return (
    <section>
      <Link to="/photo/1">Photo 1</Link>
      <Outlet name="modal" />
    </section>
  );
}
tsx
import { useRoute } from "@hamur/adapter-react";

export default function PhotoModal() {
  return <dialog open>{`Photo ${String(useRoute().params.id)}`}</dialog>;
}

With feed/@modal/(..)photo/[id].tsx, a Link to /photo/1 on /feed keeps the feed on screen and renders the photo in the modal slot. The URL changes to /photo/1, and useRoute() inside the slot is the photo's route, while the feed has its own. Back and forward restore it. A load or reload of /photo/1 renders the normal page, and any navigation that is not intercepted clears the slot. A default.<ext> in the slot is what shows when nothing is intercepted.

tsx
export default function ModalClosed() {
  return null;
}

The build fails when no page serves the intercepted path: app/pages/feed/@modal/(..)photo/[id].tsx intercepts /photo/:id, which no page serves. An intercepting folder outside a slot fails with app/pages/feed/(.)photo: an intercepting folder goes inside a slot folder (@<name>/), and (..) above the root with (..) goes above /.

Co-located components

A folder that starts with _ is never a route, so components, helpers and tests can sit next to the page that uses them.

text
app/pages/blog/
  index.tsx
  [slug].tsx
  _components/
    post-card.tsx
tsx
import { PostCard } from "./_components/post-card.tsx";

export default function Blog() {
  return <PostCard slug="hello" title="Hello" />;
}
tsx
import { Link } from "@hamur/adapter-react";

export function PostCard({ slug, title }: { slug: string; title: string }) {
  return (
    <article>
      <h2>{title}</h2>
      <Link to={`/blog/${slug}`}>Read</Link>
    </article>
  );
}

The same holds for any file whose name starts with _ and is not one of the names in Route conventions.

Nested routes

parent.tsx next to a folder parent/ makes the folder's routes its children. The parent renders Outlet where the child goes. Without a parent/index.tsx, /parent renders the parent with an empty Outlet.

tsx
import { Outlet } from "@hamur/adapter-react";

export default function Account() {
  return (
    <section>
      <h1>Account</h1>
      <Outlet />
    </section>
  );
}

The load files of every matched route start together; a load that awaits parent() waits for its parent first, which costs a round trip when the parent's data comes from a handler (Data).

A page can leave its parents. admin/print.tsx with meta = { parents: false } still serves /admin/print, but renders without admin.tsx and without any (group).tsx layout above it; a layout it names with meta.layout still wraps it. The parents' load files and middleware do not run for it, so a guard that sits only in a parent's meta.middleware no longer covers the page. Put the guard on the page itself, or in an app/pages/admin/_meta.ts folder config, which keeps covering every page below its folder. Error, not-found and pending files cover the page as before.

Root component

app/app.<ext> is an optional root component. It wraps every layout and page and renders Outlet where they go. The extension follows the library: app.tsx for React, Preact and Solid, app.vue, app.svelte, app.ts for html. Only the app's own app/ folder counts; a layer in extends cannot provide one.

tsx
import { Link, Outlet } from "@hamur/adapter-react";
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <button type="button" onClick={() => setCount(count + 1)}>Clicked {count}</button>
      <nav>
        <Link to="/">Home</Link> <Link to="/about">About</Link>
      </nav>
      <Outlet />
    </div>
  );
}

In Vue, Svelte and html the root renders Outlet too:

vue
<script setup lang="ts">
import { ref } from "vue";
import { Link, Outlet } from "@hamur/adapter-vue";

const count = ref(0);
</script>

<template>
  <div>
    <button type="button" @click="count++">Clicked {{ count }}</button>
    <nav>
      <Link to="/">Home</Link> <Link to="/about">About</Link>
    </nav>
    <Outlet />
  </div>
</template>
svelte
<script lang="ts">
  import { Link, Outlet } from "@hamur/adapter-svelte";

  let count = $state<number>(0);
</script>

<div>
  <button type="button" onclick={() => count++}>Clicked {count}</button>
  <nav>
    <Link to="/">Home</Link> <Link to="/about">About</Link>
  </nav>
  <Outlet />
</div>
ts
import { Link, Outlet } from "@hamur/adapter-html";

export default function App(): string {
  const nav = `<nav>${Link({ to: "/", children: "Home" })} ${Link({ to: "/about", children: "About" })}</nav>`;
  return `<div>${nav}${Outlet()}</div>`;
}
  • The root stays mounted when you navigate in the browser, so its state survives. Changing the layout swaps what is below it.
  • A page with meta.layout: false is still wrapped by the root.
  • useData() in the root is null, as in a layout: only a route's own load gives it data. useRoute() is the current page's route.
  • useHead in the root is applied first, so a layout or a page overrides its title and tags.
  • The error page renders without the root, so a broken root cannot hide an error.

Layouts

app/layouts/default.tsx wraps every page that does not name another layout. A layout receives the page as children. Layouts are files directly in app/layouts/, named by their file name.

tsx
import type { ReactNode } from "react";

export default function AdminLayout({ children }: { children?: ReactNode }) {
  return (
    <div>
      <nav>Admin</nav>
      {children}
    </div>
  );
}

Moving between two pages with the same layout keeps the layout's state; changing the layout unmounts the old one. An unknown layout name is a build warning and a 500 error page that names it.

The layout of a navigation is the first of these that is set: a setPageLayout call, the merged meta.layout, the appLayout of the route rule that matches (Configuration), and default when app/layouts/default.<ext> exists. meta.layout is a name, false, or { name, props }; the layout receives props in its library's idiom.

setPageLayout(name, { props, app }) changes the layout while route middleware runs. On the server app is required: pass ctx.app. In a component in the browser it renders the layout again at once and holds until the next navigation; during the server render it changes nothing, since the layout has rendered. useLayout() returns { name, props } of the layout the page renders in. See setPageLayout and useLayout.

ts
import { defineRouteMiddleware, permanentRedirect, setPageLayout } from "hamur/app";

export default defineRouteMiddleware((to, _from, ctx) => {
  if (to.path === "/home") return permanentRedirect("/");
  if (to.path === "/login") setPageLayout("guest", { app: ctx.app, props: { compact: true } });
});

useLayoutSegment() and useLayoutSegments() return the path segments below the calling layout or page, such as "blog" for a root layout at /blog/hello, and Outlet context={value} hands a value to the entries below, which read it with useOutletContext(). A pathless group shows as (group) in the segments. useResolvedPath(to, { relative: "route" }) resolves .. and ./edit against the route's path and not the URL (useResolvedPath).

tsx
import { Outlet, useLayout, useLayoutSegment, useLayoutSegments, useOutletContext, useResolvedPath } from "@hamur/adapter-react";

export function Shell() {
  const section = useLayoutSegment();
  const trail = useLayoutSegments();
  const layout = useLayout();
  return (
    <nav aria-label={`${layout.name || "none"}: ${trail.join("/")}`}>
      <p>{section ?? "home"}</p>
      <Outlet context={{ section }} />
    </nav>
  );
}

export function Crumb() {
  const { section } = useOutletContext<{ section: string | null }>();
  return <a href={useResolvedPath("..", { relative: "route" })}>{`Back to ${section ?? "home"}`}</a>;
}

Page meta

A page exports meta to configure itself. Write it with satisfies PageMeta (from hamur/app) so TypeScript checks it.

tsx
import type { PageMeta } from "hamur/app";

export const meta = {
  layout: "admin",
  middleware: ["auth"],
} satisfies PageMeta;

export default function AdminHome() {
  return <h1>Admin</h1>;
}

Every key is read in one of two ways. A run-time key is read from the page module when it loads, so it may be any value the page computes. A build key is also read by the scanner from the source text of the file, so it must be a literal. The next section says what a literal is.

KeyTypeDefaultReadMeaning
layoutstring | false | { name; props? }"default" when it existsrun timea layout name, false for none, or a name with props the layout receives
middlewarename, function, or an array of themnonerun timeroute middleware; any other value is a 500 error that names the page
ssrbooleantruerun timefalse makes this page a single-page route: the server sends the shell and the browser renders it
scriptsfalsenonerun timehtml only: a script-free page with no import map; other libraries ignore it with a build warning
searchError"error" | "strip""error"run timewhat an invalid query does (Search params)
staleTime, gcTimenumberapp.data.*run timethe client data cache of this page (Data)
headHeadInputnonerun timethis page's own head (Head); a page with ssr: false has it in the shell too, and every matched page's head is used, outermost first
keystring | (route) => stringnonerun timethe page mounts again, with its state reset, when it changes (Remounting a page)
validate(route) => boolean | HamurError | Promise<…>nonerun timefalse answers 404, a returned HamurError is thrown, true continues (Params that are checked)
paramsRecord<string, StandardSchemaV1>nonerun timea schema per param; the route then holds the outputs, and an issue answers 404
propsbooleanfalserun timetrue passes the route's params as props to the page component
appRootfalsenonerun timefalse renders this page without app/app.<ext>
documentstringthe default documentrun timethe page is written in app/documents/<name>.html, a template with <!--hamur-head--> inside <head> and <!--hamur-body--> inside <body>; an unknown name is a build warning and a 500 error
pathstringthe file's patternbuildreplaces the path the file gives
aliasstring | string[]nonebuildmore paths that serve this page, with its name and its params
redirectstring | { to; status? }nonebuildanswers this page's path with a redirect, 307 unless status (301, 302, 303, 307 or 308) says otherwise, without loading the page
parentsbooleantruebuildfalse renders the page without its parent pages and group layouts (Nested routes)
rulesRouteRulenonebuilda route rule for this page's path, with the keys of routeRules (Configuration)

When a parent and a child both export meta, the child's key replaces the parent's; arrays are not joined. The exception is head: every matched page's own head is used, outermost first, so a child adds to the head of its parent and wins where both set the same tag. In Vue the meta export goes in a plain <script lang="ts"> block next to <script setup>. In Svelte it goes in <script module>. A folder config sets run-time keys for a whole folder.

Build keys must be literals

For path, alias, redirect, parents and rules the scanner reads export const meta = { … } (a satisfies PageMeta or as const after it is fine). A literal is a string, a number, true, false, null, an array of literals, or an object with literal values; an identifier, a call, a spread, a computed key or a template with ${} is not one. export const meta = base, export { meta } and a key set through a spread give the build nothing, and hamur dev fails that page when the module's own value differs from what the build read: meta.path of app/pages/x.tsx is "/p/:id" at run time but the build read none; write it as a literal in export const meta = { … }.

tsx
import type { PageMeta } from "hamur/app";

export const meta = {
  path: "/pricing",
  alias: ["/plans", "/prices"],
} satisfies PageMeta;

export default function Pricing() {
  return <h1>Pricing</h1>;
}

path and alias are patterns with the page's own params: meta.alias "/u/:name" in app/pages/users/[id].tsx must have the params of /users/:id (id). A page with child routes keeps its file path (meta.path in app/pages/dash.tsx: a page with child routes keeps its file path). The route has one name and one chain whichever path matched. A duplicate path or alias fails the build: Duplicate route /a: app/pages/x.tsx (meta.alias) and app/pages/a.tsx.

tsx
import type { PageMeta } from "hamur/app";

export const meta = { redirect: { to: "/pricing", status: 301 } } satisfies PageMeta;

export default function Old() {
  return null;
}

redirect becomes a route rule under the page's path and each alias, below the rules of the config and of the modules, so a config rule on the same pattern wins. It is answered without loading the page and written to _redirects on the static presets. A path segment that mixes text and a param cannot be written as a rule and fails with meta.redirect in app/pages/x.tsx: the path /shop/:a-:b has a segment mixing text and a param, which a route rule cannot match; use whole-segment params. Setting both meta.redirect and meta.rules.redirect on one page fails the scan; set one of them.

Each literal key has its own build error, such as meta.redirect in app/pages/old.tsx has status 304; use 301, 302, 303, 307 or 308 and meta.parents in app/pages/admin/print.tsx must be the literal true or false.

Params that are checked

meta.params validates each named param of the matched route with a Standard Schema, and meta.validate(route) then decides with the outputs. Both run before any middleware, on the server and in the browser, since they say whether the route exists. A refusal is a 404 Page Not Found: <path>, shown by the not-found component or route boundary that covers the page, and data.issues is set in development only. A param schema that is not a Standard Schema fails with The page app/pages/users/[id].tsx has meta.params.id, which is not a Standard Schema: ~standard.validate must be a function; a validate that returns anything but a boolean or a HamurError fails with meta.validate of app/pages/users/[id].tsx must return a boolean or a HamurError (got string). A param matcher is different: it decides which route a URL is, while these refuse a route that exists.

With props: true the page component gets the validated params as props.

tsx
import type { PageMeta } from "hamur/app";

export const meta = {
  props: true,
  params: {
    id: {
      "~standard": {
        version: 1,
        vendor: "app",
        validate: (value: unknown) => (/^\d+$/.test(String(value)) ? { value: Number(value) } : { issues: [{ message: "id must be a number" }] }),
      },
    },
  },
  validate: (route) => route.params.id !== "0",
} satisfies PageMeta;

export default function User({ id }: { id: number }) {
  return <h1>{`User ${id}`}</h1>;
}

Remounting a page

A page that stays on screen while only its params change keeps its state, so a counter in /u/1 is still there on /u/2. Export meta.key to make the page mount again when a value changes:

tsx
export const meta = { key: (route) => String(route.params.id) };

The key is a string or a function of the route. Without it nothing changes. An html page is rendered again on every navigation, so it has no state to reset.

A _template.<ext> file in a pages folder wraps every page of that folder, below its layout and its parent page, and mounts again whenever the path of the page below it changes: /t/a to /t/b resets the template and the page, while /t/a/x to /t/a/y keeps them. It renders Outlet as its children, has no load, meta or error file of its own, and reads useData() as null. Two _template files in one folder are a build error.

Route middleware

Route middleware runs before a page renders: on the server for the first request, in the browser for every later navigation. It steers the visitor and guards nothing: a user can skip it in the browser, and a navigation reaches the data through handlers, not through it. A check that must hold belongs in the handler (Sessions and security). It has four outcomes:

  • return nothing to continue;
  • return redirect(to, status = 302) to redirect;
  • return false, or abortNavigation() from hamur/app, to cancel the navigation: no later middleware runs, and in the browser the page and the URL stay as they are. On the server, and on the first load of a single-page route, there is no page to stay on, so the answer is a 404 Page Not Found: <path>. abortNavigation(error) with an argument throws createError(error) instead;
  • throw createError to show the error page.
ts
import { defineRouteMiddleware, redirect } from "hamur/app";

export default defineRouteMiddleware((to, from, ctx) => {
  if (!ctx.state.get("user")) return redirect(`/login?next=${encodeURIComponent(to.fullPath)}`);
});

Nothing sets user by itself. The Forms and login guide sets it in an app plugin that asks a handler.

ts
import { abortNavigation, defineRouteMiddleware } from "hamur/app";

export default defineRouteMiddleware((to, from, ctx) => {
  if (to.path.startsWith("/checkout") && ctx.state.get("cart") === undefined) return abortNavigation();
});

A redirect to another origin needs { external: true }. Without it the target is refused: the server answers a 500 error page and sends no Location, and the browser shows the error page. A target that starts with // or \\ counts as another origin. Only a scheme in app.linkProtocols is accepted, with or without external; see Link protocols.

ts
import { defineRouteMiddleware, redirect } from "hamur/app";

export default defineRouteMiddleware((to) => {
  if (to.path === "/billing") return redirect("https://billing.example.com/", { external: true });
});

Files in app/middleware/ are named by their file name without a numeric order prefix: auth.ts is used as middleware: "auth" or middleware: ["auth"], and so is 01.auth.global.ts, which is auth and global. The run order still follows the full file name, so 01.b.global.ts runs before 02.a.global.ts. A name with an upper-case letter also answers to its kebab-case form: myAuth.ts is found as "myAuth" and as "my-auth". Two files that give the same name, such as 01.a.ts and a.ts, fail the scan, and so does an alias that equals another file's name. The old prefixed name ("01.auth") still works through 1.x and logs middleware "01.auth" is deprecated; use "auth" once in hamur dev. A file named *.global.ts runs on every navigation first, in file name order, and cannot be named in meta. A .client.ts ending limits a file to the browser. A .server.ts ending fails the build, since a client navigation would skip it and the guard would cover only the first load: app/middleware/auth.server.ts: a route middleware runs in the browser on every client navigation, so a server-only one guards only the first load; check the request in server middleware (server/index.ts) or in the handler, or drop .server to run it on both sides. The function receives the target route, the route it came from (undefined on the server and on the first browser load), and { state, app, event }: state is the same store as State, app is the app context, and event is the request's HamurEvent on the server and undefined in the browser.

One navigation runs in this order, on the server for a document and in the browser for a client navigation:

  1. the route is matched, with the param matchers;
  2. the page modules and folder configs of the chain load;
  3. meta.params, then meta.validate, of each matched page, parent first;
  4. the search schemas;
  5. the global middleware files, in file name order, then the global middleware added at run time, in the order added;
  6. the appMiddleware names of the matching route rules;
  7. per chain entry, parent first: its folder configs' middleware, then its own meta.middleware;
  8. the load files.

appMiddleware: { name: false } in a route rule takes a global middleware out of step 5 for those paths.

addRouteMiddleware(name, fn, { global, app }) adds a function at run time, and addRouteMiddleware(fn, { app }) an anonymous global one. Call it in an app plugin with the plugin's app; it returns a function that removes the middleware. A named one is found by meta.middleware like a file's. On the server a call without app throws addRouteMiddleware() needs { app } on the server; pass the plugin's app. A name that a file in app/middleware/ already uses fails with Route middleware "auth" is already defined by app/middleware/auth.ts, a name added twice with Route middleware "track" was added twice, and a name that does not match /^[A-Za-z0-9_-]+$/ is refused. A module adds a file with addRouteMiddleware of hamur/kit. See addRouteMiddleware.

ts
import { addRouteMiddleware, definePlugin } from "hamur/app";

export default definePlugin((app) => {
  const visited: string[] = [];
  addRouteMiddleware("track", (to) => {
    visited.push(to.path);
  }, { app });
});

A redirect to the URL being answered is a 500 error that names the loop. While hamur generate prerenders, a page whose middleware redirects is skipped with a warning, since the build has no session; give the route ssr: false to prerender its shell and run the middleware in the browser.

Navigation covers transitions, View Transitions, keep-alive, the loading indicator, focus and the announcer, scroll, every Link option, the prefetch triggers and Speculation Rules.

Links to your own pages are handled by the browser navigator: it fetches the page chunk and runs the page's load files, runs middleware, renders, updates the head and restores or resets the scroll position. Use Link and useRouter.

tsx
import { Link, useRouter } from "@hamur/adapter-react";

export default function Menu() {
  const router = useRouter();
  return (
    <nav>
      <Link to="/blog" prefetchOn="visibility">Blog</Link>
      <Link to="/pricing" prefetch={false}>Pricing</Link>
      <button type="button" onClick={() => router.navigate("/login", { replace: true })}>
        Sign in
      </button>
    </nav>
  );
}

Link prefetches the page chunk and the load data on hover and focus (prefetchOn="interaction", the default). prefetchOn="visibility" loads the chunks only, when the link scrolls into view, and prefetchOn={{ visibility: true, interaction: true }} does both; the data is fetched on hover, on focus and by router.prefetch(to). prefetchOn="tap" prefetches on pointerdown (touchstart where the browser has no PointerEvent), just before the click, and prefetchOn="render" loads the chunks of the link as soon as it is in the page, after hydration or a navigation. At most 4 visible or render links are prefetched at a time, when the browser is idle. prefetchDelay={100} makes a hover or focus wait that many milliseconds; one that ends sooner prefetches nothing. The browser's data-saver mode, a 2g connection and prefers-reduced-data: reduce turn the automatic prefetch off, except tap, which fetches what the click is about to fetch; router.prefetch(to) always runs. app.link.prefetchOn, app.link.prefetch and app.link.prefetchDelay in the config set these for every Link without the prop. In hamur dev visible prefetch is off and hover and focus load chunks only, unless devServer.prefetch is true. prefetch={false} or noPrefetch turns it off for one link. A hand-written <a href="/about" data-hamur-prefetch="visible"> in Markdown, CMS HTML or innerHTML is prefetched too, also when it is added after the page rendered (the navigator scans for new links once per animation frame), and so is a link inside an element that carries the attribute. A link to a page that loads as a document (scripts: false, a data-hamur-reload link, a path with a redirect rule) adds one <link rel="prefetch" as="document"> instead of chunks and data, and a link the page's speculation rules select adds none; router.prefetch(to) follows the same rule. A production build also prefetches the chunks that the page on screen loads lazily with import(): after the first mount and after each navigation, when the browser is idle, the client adds a <link rel="prefetch"> for each of them and their static dependencies, once per file, with crossorigin where app.crossOrigin sets it, under the same data-saver rules as above. A prefetched answer lives 30 seconds and is used once. Add replace to replace the history entry.

In hamur dev, a Link whose path matches no page, no GET server route, no public/ file and no proxy, redirect or rewrite route rule logs one warning per path: Link to "/abuot" matches no page or server route (rendered by app/pages/index.tsx). The server checks the links it renders and prints the warning in the terminal; the browser checks the links it renders after a navigation and logs it to the console, the terminal and the overlay log. A to computed at run time is checked like a literal one; a link with external, another origin or a scheme is not. With app.routeDiscovery: "lazy" the browser matches against the route list of the build. A production build holds neither the check nor the message.

The to of Link and of the router is an app path: Hamur adds app.baseURL in front of a path that starts with /, and leaves a relative target or a URL with a scheme as it is. To build such an href yourself, use withBase.

The router has navigate(to, { replace, scroll, external, document, shallow, state, refreshAll, refresh }), replace(to, { scroll, external, state }), back, forward and prefetch; The router lists the rest. prefetch(to, { data }) resolves to what it did: { type: "loaded", data }, { type: "redirect", location }, { type: "error", error }, { type: "chunks" } or { type: "skipped" }; { data: false } loads the chunks only. A target on another origin makes navigate and replace reject with a TypeError unless you pass external: true, which loads it as a full page load. clearError({ redirect }) takes no external and rejects such a target.

tsx
import { useRouter } from "@hamur/adapter-react";

export default function Billing() {
  const router = useRouter();
  return (
    <button type="button" onClick={() => router.navigate("https://billing.example.com/", { external: true })}>
      Billing
    </button>
  );
}

With shallow: true a navigation to the page on screen changes only the URL: useRoute().query, hash and fullPath are updated, and no middleware, load, request, scroll change or page hook runs. Use it for state kept in the query, such as a table's page number. A shallow target that is another route runs a full navigation. A direct history.pushState or history.replaceState to a URL of the same route has the same effect, and back and forward between two entries of one route that differ in query or hash update the route without a request.

tsx
import { useRoute, useRouter } from "@hamur/adapter-react";

export default function Table() {
  const router = useRouter();
  const route = useRoute();
  const page = Number(route.query.page ?? 1);
  return (
    <button type="button" onClick={() => router.navigate(`?page=${page + 1}`, { shallow: true })}>
      Page {page + 1}
    </button>
  );
}

Focus after a navigation

A client navigation does not reload the document, so the browser does not put the keyboard at the new page; a keyboard or screen reader user would stay on the link they used. After the scroll the navigator moves the focus, without scrolling, to the first of these among the elements the navigation put on screen:

  1. the element the #hash of the URL names (id, else name), given tabindex="-1" when it is not focusable;
  2. an element with autofocus;
  3. the first h1, given tabindex="-1";
  4. the app root (ctx.root), given tabindex="-1".

A tabindex="-1" the navigator added is removed when the element loses the focus; one your markup has stays. app.navigation.focus is "heading" (the default, the order above), "root" (always the app root) or "none" (the navigator moves nothing and observes nothing for it). The route announcer reads the new page to a screen reader either way.

No focus moves for a navigation that keeps the page with another query or hash only (the same route and params), shallow: true, refreshAll and refresh, keepFocus: true, scroll: false, or a link inside an element with data-hamur-keepfocus (data-hamur-keepfocus="false" on a closer element turns it back on). The focus also stays when, after the update, it is in a text-entry control (an input that is not a button, checkbox, radio, range, color, file or image, a textarea, a select, a contenteditable element, or an element with role="textbox", "searchbox" or "combobox"), such as a search box that navigates as you type, and when your own code focused an element of the new page during the render. Under a view transition (app.viewTransition) the focus moves once the update callback has finished.

Announcing a page

A screen reader user whose focus did not move still has to learn that the page changed. After the scroll and the focus step the navigator writes one text into a hidden live region, #__hamur_announcer (aria-live="polite", aria-atomic="true", role="status"): the page's document.title, else the text of the first h1 among the elements the navigation put on screen, else the path. The region is cleared first and the text is written 50 ms later, so the same text twice in a row is still read. Under a view transition the text is written once the update callback has finished.

app.routeAnnouncer is { politeness: "polite" } by default. "assertive" gives aria-live="assertive" and role="alert", "off" gives aria-live="off" and no role, and false creates no region and announces nothing. Any other value fails at load with app.routeAnnouncer.politeness must be "polite", "assertive" or "off" (got "loud"). Nothing is announced on the first load, for a navigation that keeps the page with another query or hash only, shallow: true, refreshAll and refresh.

To say something other than the title, call useRouteAnnouncer().set("3 results") (or polite(...), assertive(...)) while the page renders or when it mounts: during a navigation, before its announcement, the call replaces that navigation's text; at any other time it announces at once. To style the region or have it inside your layout, render <RouteAnnouncer /> once in the root layout: the navigator creates no region of its own while one is mounted, and creates it again when it unmounts. The server writes the region without a style attribute, so a strict style-src is enough; the browser hides it through element.style unless you pass class or style.

For updates inside a page (a saved form, a filter that changed the results) useAnnouncer() writes into #__hamur_announcer_polite or #__hamur_announcer_assertive, two regions that never change their aria-live, created on body on the first call: const { assertive } = useAnnouncer(); assertive("Saved"). <Announcer /> renders both regions in the app. See useRouteAnnouncer.

Search params

A page may export search, a Standard Schema (the interface Zod, Valibot and ArkType implement) for its query string. Hamur validates the query before route middleware, on the server and in the browser, and every reader gets the result with defaults filled in: ctx.search in a load, to.search in middleware, and useRoute().search in a component. A page without search has search equal to query (with app/search.ts, what its parse returns). In a Vue page the export goes in the plain <script lang="ts"> block, in Svelte in <script module>.

tsx
import { Link, useSearch } from "@hamur/adapter-react";
import type { PageMeta } from "hamur/app";
import { schema } from "../utils/standard-schema.ts";

export const search = schema<{ page: number; tab?: string }>(
  { type: "object", properties: { page: { type: "integer" }, tab: { type: "string" } } },
  (value) => {
    const query = (value ?? {}) as { page?: unknown; tab?: unknown };
    const page = query.page === undefined ? 1 : Number(query.page);
    if (!Number.isInteger(page) || page < 1) return { issues: [{ message: "page must be a whole number from 1", path: ["page"] }] };
    return { value: { page, ...(typeof query.tab === "string" ? { tab: query.tab } : {}) } };
  },
);

export const searchRetain = ["tab"];

export const meta = { searchError: "strip" } satisfies PageMeta;

export default function Products() {
  const page = useSearch((current) => Number(current.page));
  return (
    <nav>
      <button type="button" onClick={() => page.set((prev) => ({ ...prev, page: Number(prev.page) + 1 }))}>
        Page {page.value + 1}
      </button>
      <Link to="/products" query={(prev) => ({ ...prev, page: 1 })}>First page</Link>
    </nav>
  );
}
  • When the query does not validate, the page answers 400 Invalid search params, with data.issues as a list of { path, message }. meta.searchError: "strip" drops the top-level keys the issues name and validates again; it fails as "error" when that does not help. The innermost page's value wins.
  • Parent routes validate first: each schema in the chain gets the query and its output is merged over the earlier ones.
  • After hamur typegen, the output type of the schema is the type of search for that route.
  • useSearch(select?) returns { value, set }. set(next | (prev) => next, { replace = true }) navigates to the page on screen with that search. It runs the guards and the load files whose searchKeys changed, and replace: false adds a history entry. A selected value is compared by deep equality, so a component updates only when its part changes. router.navigate({ query: (prev) => next }) does the same without the hook, and Link takes query={(prev) => next}.
  • A key is left out of a URL written this way when validating the search without it gives the same value, so set({ page: 1 }) with a default of 1 writes /products. A query string you write by hand is never changed.
  • The default codec reads and writes flat URLSearchParams. A key that the schema's input JSON Schema types as an object, array, number or boolean is written as JSON (tags=["a","b"]) and parsed back. app/search.ts replaces the codec for the whole app, on the server and in the browser. A parse that throws makes the search invalid, with the same 400.
  • export const searchRetain = ["tab"] in a page carries those keys, when the page on screen has them, to every Link and navigate() built from that page or its children, unless the target sets them.
ts
import { defineSearchCodec } from "hamur/app";

export default defineSearchCodec({
  parse: (search) => {
    const raw = new URLSearchParams(search).get("q");
    return raw ? (JSON.parse(atob(raw)) as Record<string, unknown>) : {};
  },
  stringify: (value) => (Object.keys(value).length ? `q=${btoa(JSON.stringify(value))}` : ""),
});

The router

useRouter() has more than navigate. These work in the browser; on the server resolve, getRoutes, hasRoute and currentRoute work and the rest do nothing or throw only available in the browser.

CallDoes
push(to, options)the same as navigate
go(delta), back(), forward(), canGoBack()history; canGoBack() is false on the first entry of the session
resolve(to){ href, path, name?, params, query, hash } of an app path or a { name, params } location, without navigating
beforeEach(guard)runs guard(to, from) on every client navigation after route middleware. false cancels, a path or a location redirects, a throw shows the error page
afterEach(hook)runs hook(to, from, failure?) after the commit, or with failure.type "cancelled" or "superseded"
onError(handler)gets every error a navigation shows or reloads for, before the error page
isReady()resolves once the first page has hydrated or mounted
getRoutes(), hasRoute(name), currentRoutethe page routes as { name, path }, a check for one, and the route on screen. There is no addRoute

beforeEach, afterEach and onError return a function that removes them.

tsx
import { onAfterNavigate, onBeforeNavigate, useRoute, useRouter } from "@hamur/adapter-react";
import { useEffect } from "react";

export default function Shell() {
  const router = useRouter();
  const route = useRoute();

  useEffect(() => {
    const removeGuard = router.beforeEach((to) => (to.path.startsWith("/admin") && route.meta.public !== true ? { name: "login" } : undefined));
    const removeAfter = router.afterEach((to, from, failure) => {
      if (!failure) console.log(`${from.path} to ${to.path}`);
    });
    const removeError = router.onError((error, to) => console.error(`navigation to ${to?.path} failed`, error));
    return () => {
      removeGuard();
      removeAfter();
      removeError();
    };
  }, [router, route.meta.public]);

  onBeforeNavigate((navigation) => {
    if (navigation.type === "leave" && document.hidden) navigation.cancel();
  });
  onAfterNavigate((navigation) => console.log(navigation.type, navigation.to?.path));

  const target = router.resolve({ name: "blog-slug", params: { slug: "hello" } });
  return (
    <a href={target.href} onClick={(event) => (event.preventDefault(), void router.push(target.path, { refreshAll: true }))}>
      {target.path}
    </a>
  );
}

navigate also takes refreshAll: true, which runs every load again and refreshes every mounted useAsyncData, past the prefetch and the client data cache, and refresh: ["posts:list"], which treats those keys as changed for this navigation. document: true loads the target as a document. To keep the scroll position of a navigation, call disableScrollHandling() in onNavigate, onAfterNavigate or the setup of the page you navigate to; called at another time it does nothing.

onBeforeNavigate(fn), onNavigate(fn) and onAfterNavigate(fn) run a function on each client navigation while the component is mounted. The navigation they get has type ("enter", "link", "goto", "popstate", "form" or "leave"), from, to (null when there is no page on that side) and cancel(). onBeforeNavigate may call cancel(); for leave, when the document unloads, the browser asks the user to stay. The order of one navigation, its page hooks included, is in the API reference. A page module may export onEnter(route), onStay(route) and onLeave(route), which run in the browser after a navigation committed; see hamur/app.

A script outside the app (analytics, a widget) listens on document instead: hamur:beforenavigate fires after onBeforeNavigate and is cancelable (event.preventDefault() is navigation.cancel()), hamur:navigate after onNavigate and before the page changes, and hamur:afternavigate after onAfterNavigate and once with type: "enter" after the first page mounted. Each event.detail is { type, from, to, delta? } with from and to as full paths (null where the hook's are null). A hash-only or shallow navigation fires none. document.addEventListener("hamur:afternavigate", (event) => track(event.detail.to)) is typed once the app imports hamur.

useRoute() also tells how the page came to be: status (the status of the document or of the error page), renderMode ("ssr", "spa" or "prerendered"), and navigationType.

redirect(to, { document: true }) returned from a load or middleware loads the target as a document, so cookies set on the answer are kept and the server renders the target; { replace: true } replaces the history entry instead of adding one. prefetch(to, { data }) in the router resolves to what it loaded, described under Navigation.

Scroll

A navigation scrolls in this order: back and forward go to the position saved for that history entry; else a #hash goes to its element; else a page with meta.scrollToTop: false keeps the position; else the page goes to the top. scrollToTop may be a function of the two routes, which says "keep" for pages that belong together:

ts
export const meta = { scrollToTop: (to, from) => to.params.id !== from.params.id };

It also goes in a folder config, so a whole section keeps the position between its pages. A scrollBehavior (below) replaces this rule.

A scrolling element that is not the window, such as a sidebar, is saved and restored when you give it an id: <nav data-hamur-scroll-restore="nav">. Its position is stored with the window's when a navigation commits and when the document unloads, and comes back on back, forward and reload. Ids are per document, the first element of a repeated id is used, and an id the new page does not render is skipped.

app.navigation.scrollKey: "path" keeps the saved positions per pathname instead of per history entry, so following a link to a page you left scrolled restores where you were, unless the link has a #hash or the navigation passes scroll: false.

Router options

app/router.options.ts default-exports defineRouterOptions({ scrollBehavior }) from hamur/app. scrollBehavior(to, from, saved) runs on every client navigation in place of the default scroll. saved is the position stored for a back or forward and undefined otherwise. It returns { type: "position", x, y }, { type: "hash", id }, { type: "top" } or { type: "none" }, or a promise of one that the navigator awaits before it scrolls (during a view transition that wait is inside the transition's update, so the promise must not wait for a frame or for page:transition:finish). It does not run for a navigate with scroll: false or after disableScrollHandling(), and an error it throws is logged and nothing scrolls. It is client code; the server never imports it. Each layer may have the file, and later keys win.

ts
import { defineRouterOptions } from "hamur/app";

export default defineRouterOptions({
  scrollBehavior(to, from, saved) {
    if (saved) return { type: "position", x: saved.x, y: saved.y };
    if (to.hash) return { type: "hash", id: to.hash.slice(1) };
    return to.path === from.path ? { type: "none" } : { type: "top" };
  },
});

The other router settings are data, so they are keys of hamur.config.ts that the server, the static preset and the build read too:

SettingKey
history modeapp.history: "browser" (default) or "hash". "hash" keeps the path in location.hash (#/about), needs ssr: false, and the static presets serve index.html for every path
caseapp.caseSensitive: false matches in any case and answers 301 to the lower-case path
trailing slashapp.trailingSlash: "ignore" (default), "redirect", "always" or "strict" (Files and routes)

memoryHistory(initial) from hamur/app gives a navigator a session history without window, for tests and embedded widgets: the entries are kept in memory, starting at initial. See memoryHistory.

ts
import { memoryHistory } from "hamur/app";

const history = memoryHistory("/blog");
history.push("/blog/hello", null);
history.go(-1);
export const at = history.location;

Leaving a page

Three tools guard a page that has unsaved work, from the weakest to the strongest:

  • onBeforeRouteLeave(fn) and onBeforeRouteUpdate(fn) run while a component is mounted. fn(to, from) answers as a beforeEach guard does. The first runs when the navigation leaves the page the component belongs to, the second when that page stays with new params or a new query. They run before route middleware. A guard in a layout or the root never runs.
  • useBlocker(shouldBlock) returns { state, location, proceed, reset }. When shouldBlock({ from, to, type }) is true, the navigation waits in the state "blocked" until your dialog calls proceed() or reset(). With beforeUnload (on by default), closing or reloading the tab shows the browser's own dialog while it blocks. usePreventNavigate(fn) is the shorter form that answers with a boolean.
  • onBeforeNavigate(fn) can call navigation.cancel().
tsx
import { onBeforeRouteLeave, useBlocker, useRouter, useSnapshot } from "@hamur/adapter-react";
import { useRef, useState } from "react";

export default function Editor() {
  const [dirty, setDirty] = useState(false);
  const note = useRef<HTMLTextAreaElement>(null);
  const router = useRouter();
  const blocker = useBlocker(({ to }) => dirty && to !== null);

  onBeforeRouteLeave((to) => (to.path === "/login" ? true : !dirty));
  useSnapshot("note", {
    capture: () => note.current?.value ?? "",
    restore: (value) => void (note.current && (note.current.value = value)),
  });

  return (
    <form>
      <textarea ref={note} onChange={() => setDirty(true)} />
      <button type="button" onClick={() => router.pushState("", { step: 2 })}>Next step</button>
      {blocker.state === "blocked" && (
        <dialog open>
          Leave without saving? <button type="button" onClick={blocker.proceed}>Leave</button> <button type="button" onClick={blocker.reset}>Stay</button>
        </dialog>
      )}
    </form>
  );
}

Every guard must let a navigation go; the first that blocks ends the list. A back or forward that is cancelled is undone with history.go, so the URL stays. A form's own navigation is never blocked, and a hash-only navigation runs none of these. Nothing here guards data: it steers the visitor, and the check that matters is in the handler.

History state and snapshots

navigate(to, { state }), replace(to, { state }) and <Link state={…}> store a serializable object with the new history entry. useRoute().state reads it ({} when none), and it survives a reload. At most 65,536 characters serialized; a larger or unserializable state rejects with a TypeError before any guard runs. Treat it as input: a user can edit history entries.

router.pushState(url, state) and router.replaceState(url, state) add or change an entry without a guard, middleware, load or request, whatever page url matches; "" keeps the URL. The page on screen stays, with useRoute().state set. Back from it restores the earlier state, and a reload of it loads its URL as a document. Use it for a modal or a step that has its own history entry.

tsx
import { useRoute, useRouter } from "@hamur/adapter-react";

export default function Wizard() {
  const route = useRoute();
  const router = useRouter();
  const step = Number(route.state.step ?? 1);
  return (
    <div>
      <p>Step {step}</p>
      <button type="button" onClick={() => router.pushState("", { step: step + 1 })}>Next</button>
      <button type="button" onClick={() => router.replaceState("", { step })}>Keep</button>
      <button type="button" onClick={() => router.navigate("/wizard/done", { state: { from: step } })}>Finish</button>
    </div>
  );
}

useSnapshot(key, { capture, restore }) keeps a value of the page per history entry, such as text typed into a form. When the page leaves an entry, capture() is stored; when back, forward or a reload brings the entry back, restore(value) runs. The value must be serializable and at most 65,536 characters. It is kept in memory and in sessionStorage (item hamur:snapshot, the last 100 entries), so capture() must never return a secret. A cookie change drops every stored value. The sample above saves a textarea this way.

The route table

A route table in code

Files are the default way to declare routes. app/routes.ts changes the table after the scan and after the modules' pages:extend: it default-exports a function that gets the scanned RouteRecord[] and returns the table. route(path, file, children?), index(file), group(file, children) (a pathless layout) and prefix(path, children) from hamur/kit build records. A path without a leading / is relative to its parent route's; file is relative to app/. Typegen, the manifest and the conformance suite treat the result as scanned routes.

ts
import { group, index, prefix, route, type RouteRecord } from "hamur/kit";

export default (scanned: RouteRecord[]): RouteRecord[] => [
  ...scanned,
  index("screens/home.tsx"),
  route("legal", "screens/legal.tsx", [route("terms", "screens/terms.tsx")]),
  group("screens/(shell).tsx", [route("settings", "screens/settings.tsx")]),
  ...prefix("/v2", [route("about", "screens/about.tsx")]),
];

The records go through the checks scanned ones do (pattern, duplicate path, duplicate name), with the message naming app/routes.ts. A file that does not exist fails with app/routes.ts: the route /gone renders app/screens/gone.tsx, which does not exist, and a default export that is not a function with app/routes.ts must default-export a function (scanned: RouteRecord[]) => RouteRecord[] (got an array). Only the app's own app/ has a route table; a layer cannot provide one.

dir in hamur.config.ts renames the folders, relative to app/: { pages?: string | string[]; layouts?: string; middleware?: string }, with the defaults pages, layouts and middleware. With a list in dir.pages, each folder is its own tree, and two of them serving one path fail the build with Duplicate route /about: … naming both files. See Configuration.

Lazy discovery and server bundles

By default the browser entry holds every route record. app.routeDiscovery: "lazy" keeps in it only the root and the pages that can match any first segment (a param, a catch-all), and writes the others as one file per first path segment, <baseURL><buildAssetsDir>manifest/<build id>/<segment>.json. The document carries the records of its own first segment, so hydration needs no request, and a client navigation to another segment loads that file first. The files are public build assets with cache-control: public, max-age=31536000, immutable, and hamur dev ignores the setting.

build.serverBundles splits the server build for serverless hosts. Each key is a branch id and each value route-rule patterns matched against the page patterns; hamur build writes a branch's pages, load files and their boundary, template and folder-config modules to .output/server/<id>/index.mjs, which the main entry imports on the first request that needs it. A page no pattern names stays in the main bundle, and so do layouts, handlers and middleware. A page that two branches name fails the build with build.serverBundles: /admin/users is in "admin" and "users", and a branch that names no page is a warning.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  dir: { pages: ["pages", "admin-pages"] },
  app: { routeDiscovery: "lazy", notFoundMode: "fuzzy", caseSensitive: false, trailingSlash: "strict" },
  build: { serverBundles: { admin: ["/admin", "/admin/**"] } },
});

A Link, navigate(), replace(), navigateTo(), redirect() and sendRedirect target may carry only a scheme listed in app.linkProtocols: http, https, mailto, tel and sms by default. The scheme is read as the browser reads it, so " JaVa\tScript:x" is javascript. Other targets are refused:

  • a Link renders href="#", and hamur dev logs Link target "javascript:…" blocked by app.linkProtocols once per scheme;
  • navigate(), navigateTo(), redirect() and sendRedirect throw a HamurError with status 400 and the same message, and a load that returns such a redirect renders the error page with 400.

A listed scheme other than http and https, such as mailto:, is an external target: it needs { external: true } in navigate(). Add a scheme to app.linkProtocols to allow it (Configuration).

navigateTo(to, { replace, external, redirectCode }) of hamur/app (every adapter re-exports it) works outside components too: in the browser it is navigate, or replace with replace: true; during server rendering and in route middleware it throws the redirect redirect(to, { status: redirectCode }) returns, with status 302 by default.

A link is left to the browser when:

  • it has a target other than _self, a download attribute, rel="external" or data-hamur-reload, or is clicked with a modifier key;
  • it points to another origin or to a path outside app.baseURL;
  • its path is a server route that answers GET and no page has the same path, a file in public/, or a path with a proxy route rule;
  • its path ends in a file extension, as in /feed.xml, and no page claims that extension.

A navigation to a path with a redirect route rule is a full page load, so the server decides. A navigation that matches no route, or whose page chunk fails to load, becomes a full page load.