# Routing details

The rules, options and build errors behind the [Routing](/routing) guide. `.tsx` stands for the page extension of your library.

## Files and routes

| File in `app/pages/`       | Path                  | What it matches                                                                   |
| -------------------------- | --------------------- | --------------------------------------------------------------------------------- |
| `index.tsx`                | `/`                   |                                                                                   |
| `blog/[slug].tsx`          | `/blog/:slug`         | a required param                                                                  |
| `users/[[id]].tsx`         | `/users/:id?`         | an optional param                                                                 |
| `docs/[...path].tsx`       | `/docs/**:path`       | a catch-all, one or more segments                                                 |
| `files/[[...path]].tsx`    | `/files/**:path?`     | an optional catch-all, zero or more segments                                      |
| `shop/[category]-[id].tsx` | `/shop/:category-:id` | several params in one segment                                                     |
| `items/[id=integer].tsx`   | `/items/:id`          | a param that passes a [matcher](#param-matchers)                                  |
| `(marketing)/pricing.tsx`  | `/pricing`            | a `(group)` folder adds nothing to the path                                       |
| `[...slug].tsx`            | every unmatched path  | your own 404 page; it answers 200 unless it throws `createError({ status: 404 })` |

| Rule               | What happens                                                                                                                         |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
| params             | a string, decoded with `decodeURIComponent`; a catch-all is a `string[]`. A malformed escape answers 400                             |
| best match         | compared segment by segment: static, text mixed with params, a required param, an optional param, a catch-all, an optional catch-all |
| ignored files      | a name that starts with `_` or `.`, except the [route conventions](#route-conventions); `*.test.*`, `*.spec.*` and `*.d.ts`          |
| two pages, one URL | a build error that names both files ([HAMUR_E1043](/errors/HAMUR_E1043))                                                             |
| not HTML           | a request that does not prefer HTML and matches no page gets a JSON 404                                                              |

````tsx [react/docs-page.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>
}
````

### Trailing slashes and case

A page matches with or without one trailing slash, in the case it is written in. Two config keys change that. Server routes are never redirected, and a path no page matches stays a 404.

| `app.trailingSlash`  | What a page request gets                                                                                                                                                                                                                            |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"ignore"` (default) | `/about` and `/about/` both answer                                                                                                                                                                                                                  |
| `"redirect"`         | `/about/` is a 308 to `/about`, with the query                                                                                                                                                                                                      |
| `"always"`           | `/about` is a 308 to `/about/`, with the query. Links, navigations and canonical links use the slash too. Paths with a file extension and `/_hamur/` are left alone. The static presets write the rule to `_redirects` for each page without params |
| `"strict"`           | `/about/` is a 404, except for `/`                                                                                                                                                                                                                  |

`app.caseSensitive: false` matches a page in any case and answers `/About` with a 301 to `/about`, before any slash redirect. A client navigation goes to the lower-case path.

### Param matchers

`[id=integer]` takes the page only when the matcher 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.

- It works on every param form: `[[id=integer]]`, `[...path=segments]`, `[[...path=segments]]` and `[sku=integer]-[color]`.
- A catch-all's matcher gets its segments joined by `/`. An absent optional param is not checked.
- A param with a matcher comes before the same param without one; 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.
- A handler `route` is a plain path and takes no matcher.
- `match` must return a boolean, or the request fails with `app/params/integer.ts: match must return a boolean (got object)`. A matcher with no file is [HAMUR_E1041](/errors/HAMUR_E1041).

### Escapes

`[x+HH]` (two hex digits), `[u+HHHH]` (four) and `[.]` write a character that a file name cannot hold or that would mean something else. They are always plain text.

| 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`). These are build errors: a malformed escape ([HAMUR_E1004](/errors/HAMUR_E1004)), an escaped `/` ([HAMUR_E1005](/errors/HAMUR_E1005)), control character ([HAMUR_E1006](/errors/HAMUR_E1006)) or surrogate ([HAMUR_E1007](/errors/HAMUR_E1007)), and an optional param beside another param ([HAMUR_E1010](/errors/HAMUR_E1010)).

## Route conventions

A few names in `app/pages/` are not pages. Most come in two forms: a suffix of a page file, and a file in a folder.

| File                                        | What it is               | Covers                                                                                             |
| ------------------------------------------- | ------------------------ | -------------------------------------------------------------------------------------------------- |
| `dash.error.tsx`, `dash/_error.tsx`         | route boundary           | `dash/_error.tsx` the routes in `dash/` and below, not `dash` itself; `dash.error.tsx` also `dash` |
| `shop.not-found.tsx`, `shop/_not-found.tsx` | not-found component      | the same                                                                                           |
| `slow.pending.tsx`, `dash/_pending.tsx`     | pending component        | the same                                                                                           |
| `_not-found.tsx` (in `app/pages/`)          | root not-found component | every route, and a URL no page matches                                                             |
| `t/_template.tsx`                           | route template           | the routes of `t/`, see [Remounting a page](#remounting-a-page)                                    |
| `admin/_meta.ts`                            | folder config            | every route in `admin/` and below                                                                  |
| `(app).tsx` beside `(app)/`                 | pathless group layout    | the routes in `(app)/`                                                                             |
| `@team/index.tsx`, `@team/default.tsx`      | slot                     | the page beside the `@team` folder                                                                 |
| `(..)photo/[id].tsx` in a slot              | intercepting route       | see [Intercepting routes](#intercepting-routes)                                                    |

- A route takes the nearest file of each kind, walking up from the page: its own suffix file, its folder's `_<kind>`, the parent page's suffix file, and so on up to `app/pages/`. A `(group)` and an `@slot` folder count as folders here.
- The extension is the one of your pages. `_meta.ts` takes `.ts`, `.mts`, `.js` or `.mjs`.

| Slip                                       | Build error                        |
| ------------------------------------------ | ---------------------------------- |
| a suffix file without its page             | [HAMUR_E1033](/errors/HAMUR_E1033) |
| two files of one kind                      | [HAMUR_E1034](/errors/HAMUR_E1034) |
| a name one letter off, such as `_eror.tsx` | [HAMUR_E1030](/errors/HAMUR_E1030) |
| `_loading.tsx`, the Next.js name           | [HAMUR_E1038](/errors/HAMUR_E1038) |
| `_layout.tsx`, the Remix name              | [HAMUR_E1039](/errors/HAMUR_E1039) |
| `_meta` with a wrong extension             | [HAMUR_E1036](/errors/HAMUR_E1036) |

### Route boundaries and not-found components

A route boundary shows the error of one route inside the page, so the layout and the parent pages stay on screen. It reads the error with `useError()` and leaves with `clearError()`, which runs the URL again, or `clearError({ redirect })`.

| Question              | Answer                                                                                                                                                                                                |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| what it catches       | what the route's `load`, its middleware, `meta.params`, `meta.validate`, a `search` schema or the component's render throws                                                                           |
| where it shows        | in the place of the failing route: a failing `dash/broken` inside `dash`, a failing `dash` inside the layout                                                                                          |
| what it never catches | a redirect, a cancelled navigation, `createError({ fatal: true })`, an error of a layout or the root component, a malformed path, its own error; the [error page](/errors#the-error-page) shows those |
| a 404                 | the covering not-found component wins over a route boundary at any level; without one, the nearest route boundary takes it. Throw [`notFound()`](/errors#status-helpers) in a `load`                  |
| several failing loads | the outermost failing route wins and the others are logged                                                                                                                                            |
| status and hook       | the answer has the error's status; `page:error` runs before the boundary renders                                                                                                                      |
| a URL no page matches | `app/pages/_not-found.tsx`, inside the root and the `default` layout. `app.notFoundMode: "fuzzy"` [changes that](/errors#a-url-no-page-matches)                                                       |

### Pending components

A pending component shows when a client navigation still loads after 1000 ms (`app.navigation.pendingMs`). It takes the place of the first page entry that is not on screen yet; the entries above it stay mounted.

- It never shows for the first load, a shallow navigation, `refresh()` or on the server.
- `useNavigation()` gives it `state: "loading"` and `to`, the target. `useRoute()` is still the page on screen and `useData()` is `null`.
- A newer navigation replaces it. A cancelled navigation puts the page on screen back.

### Folder config

`app/pages/admin/_meta.ts` exports `meta`, which applies to every route in `admin/` and below, also in `(group)` folders and slots.

- A page's key wins over a folder's, and a deeper folder's over an outer one's.
- `middleware` is not replaced: the folder's runs first, then the page's.
- It holds run-time keys of [page meta](#page-meta) only ([HAMUR_E1119](/errors/HAMUR_E1119)). It has no default export ([HAMUR_E1117](/errors/HAMUR_E1117)) and must export `meta` ([HAMUR_E1118](/errors/HAMUR_E1118)).

### Pathless group layouts

`(app).tsx` beside a folder `(app)/` is the layout of the routes in that folder and adds nothing to the path: `(app)/settings.tsx` is `/settings`.

````tsx [routing/(app).tsx]
import { Outlet } from "@hamur/adapter-react"

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

- It takes `meta`, whose `middleware` runs as a parent page's does, `(app).load.ts` for its data, and the suffix files above.
- It is never matched alone and has no route to navigate to.
- 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 is [HAMUR_E1042](/errors/HAMUR_E1042).

### Slots

A slot shows a second page next to the main one. A folder `@team` beside a page `dash.tsx` is a slot of that page, which renders it with `<Outlet name="team" />`.

````tsx [routing/dash.tsx]
import { Outlet } from "@hamur/adapter-react"

export default function Dash() {
  return (
    <section>
      <main>
        <Outlet />
      </main>
      <aside>
        <Outlet name="team" />
      </aside>
    </section>
  )
}
````

````tsx [routing/dash/@team/index.tsx]
export default function TeamIndex() {
  return <p>Your team</p>
}
````

When the URL has no page in the slot, `default.tsx` renders:

````tsx [routing/dash/@team/default.tsx]
export default function TeamDefault() {
  return <p>Pick a team</p>
}
````

- Each slot is matched against the same URL as the main page: `dash/@team/settings.tsx` renders at `/dash/settings`. The route names are `dash@team` and `dash@team-settings`.
- A slot page's `load` runs beside the main one. `useData()` in the slot reads its own data; `useRoute()` is the main route.
- A slot with no page and no `default` renders nothing and logs [HAMUR_W2014](/errors/HAMUR_W2014) in `hamur dev`. After a client navigation it keeps its last page while the page that owns it stays on screen.
- The name matches `/^@[a-z][a-z0-9-]*$/`. Any other `@` folder, such as `@[user]`, is a path segment.

| Slip                                      | Build error                        |
| ----------------------------------------- | ---------------------------------- |
| `dash/@sidebar.tsx`, a named view of Nuxt | [HAMUR_E1018](/errors/HAMUR_E1018) |
| a slot with no page beside its folder     | [HAMUR_E1015](/errors/HAMUR_E1015) |
| a slot inside a slot                      | [HAMUR_E1013](/errors/HAMUR_E1013) |
| a slot page whose URL no main page serves | [HAMUR_E1045](/errors/HAMUR_E1045) |

### Intercepting routes

An intercepting route opens a link over the page it is on, such as a photo over a feed. It is a page in a `(.)`, `(..)` or `(...)` folder inside a slot.

````tsx [routing/feed.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 [routing/feed/@modal/(..)photo/[id].tsx]
import { useRoute } from "@hamur/adapter-react"

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

The slot needs a `default` for the time nothing is open:

````tsx [routing/feed/@modal/default.tsx]
export default function ModalClosed() {
  return null
}
````

| Prefix  | The path starts                |
| ------- | ------------------------------ |
| `(.)`   | at the path of the slot's page |
| `(..)`  | one segment above it           |
| `(...)` | at `/`                         |

- A `Link` to `/photo/1` on `/feed` keeps the feed on screen, shows the photo in the slot and changes the URL. Back and forward restore it.
- A load or reload of `/photo/1` renders the normal page. Any other navigation clears the slot.
- `useRoute()` in the slot is the photo's route, while the feed has its own. Groups and slots do not count as segments.
- Build errors: no page serves the path ([HAMUR_E1044](/errors/HAMUR_E1044)), the folder is outside a slot ([HAMUR_E1016](/errors/HAMUR_E1016)), and `(..)` goes above `/` ([HAMUR_E1017](/errors/HAMUR_E1017)).

### Co-located components

A folder or file whose name starts with `_` is never a route, unless it is one of the [route conventions](#route-conventions). Components, helpers and tests can sit next to the page that uses them.

```
app/pages/blog/
  index.tsx
  [slug].tsx
  _components/
    post-card.tsx
```

````tsx [routing/blog/_components/post-card.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>
  )
}
````

## 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`.
- The `load` files of all matched routes start together. One that awaits `parent()` waits for it first, which can [cost a round trip](/data#a-chain-of-loads-costs-round-trips).
- `meta = { parents: false }` on `admin/print.tsx` still serves `/admin/print`, but without `admin.tsx` and group layouts. A layout it names with `meta.layout` still wraps it, and the error, not-found and pending files cover it.

> **Warning.** The parents' `load` files and middleware do not run for a page with `parents: false`. Put a guard on the page itself or in the folder's `_meta.ts`, which keeps covering it.

## Root component

`app/app.tsx` 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 and Angular.

Vue:

````vue [vue/app-root.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:

````svelte [svelte/app-root.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>
````

html:

````ts [app-root.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>`
}
````

Angular:

````ts [angular/app-root.ts]
import { Component, signal } from "@angular/core"
import { Link, Outlet } from "@hamur/adapter-angular"

@Component({
  imports: [Link, Outlet],
  template: `<div>
    <button type="button" (click)="count.set(count() + 1)">Clicked {{ count() }}</button>
    <nav>
      <a hamurLink="/">Home</a> <a hamurLink="/about">About</a>
    </nav>
    <hamur-outlet />
  </div>`,
})
export default class App {
  readonly count = signal(0)
}
````

- It stays mounted on a client navigation, so its state survives a change of layout.
- A page with `meta.layout: false` still has it; `meta.appRoot: false` leaves it out. The [error page](/errors) renders without it.
- `useData()` in it is `null`. `useRoute()` is the current page's route.
- Its `useHead` is applied first, so a layout or a page wins.
- Only the app's own `app/` folder has one; a layer cannot provide it.

## Layouts

Layouts are files directly in `app/layouts/`, named by their file name. Two pages with the same layout keep its state; a change of layout unmounts the old one. An unknown layout name is a build warning and a 500 error page that names it. A layout can have [its own `load`](/data#layout-loads).

````tsx [react/admin-layout.tsx]
import type { ReactNode } from "react"

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

The first of these that is set is the layout of a navigation:

| Order | Where                                                                                           |
| ----- | ----------------------------------------------------------------------------------------------- |
| 1     | a [`setPageLayout`](/api-reference/app#setpagelayout) call                                      |
| 2     | `meta.layout` of the page, its parents or a folder config: a name, `false` or `{ name, props }` |
| 3     | `appLayout` of the matching route rule ([Configuration](/configuration))                        |
| 4     | `default`, when `app/layouts/default.tsx` exists                                                |

Route middleware can choose the layout:

````ts [routing/guest-layout.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", ctx, { props: { compact: true } })
})
````

A layout can read where it is. [`useLayoutSegment` and `useLayoutSegments`](/api-reference/adapters#uselayoutsegment-uselayoutsegments) give the path segments below it, a group as `(group)`. [`useOutletContext`](/api-reference/adapters#useoutletcontext) reads the `context` of the `Outlet` above, [`useResolvedPath`](/api-reference/adapters#useresolvedpath) resolves `..`, and [`useLayout`](/api-reference/adapters#uselayout-setpagelayout) returns the layout's name and props.

````tsx [routing/layout-segments.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. `satisfies PageMeta` (from `hamur/app`) lets TypeScript check it. A **run-time** key may be any value the page computes; a **build** key [must be a literal](#build-keys-must-be-literals).

| Key                                  | Type                                             | Default                    | Read     | Meaning                                                                                                                                             |
| ------------------------------------ | ------------------------------------------------ | -------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `layout`                             | `string \| false \| { name; props? }`            | `"default"` when it exists | run time | the [layout](#layouts)                                                                                                                              |
| `middleware`                         | a function or an array of them                   | none                       | run time | [route middleware](#route-middleware)                                                                                                               |
| `ssr`                                | `boolean \| "data-only" \| (ctx) => …`           | `true`                     | run time | `false` renders the page in the browser only; `"data-only"` runs the loads on the server ([Rendering modes](/rendering-modes))                      |
| `scripts`                            | `false`                                          | none                       | run time | a page with no import map, entry or payload script; the route rule `scripts: false` does the same for a pattern                                     |
| `searchError`                        | `"error" \| "strip"`                             | `"error"`                  | run time | what an invalid query does ([Search params](#search-params))                                                                                        |
| `staleTime`, `gcTime`                | `number`                                         | `app.data.*`               | run time | the [client data cache](/data#the-client-data-cache) of this page                                                                                   |
| `head`                               | `HeadInput`                                      | none                       | run time | the page's own [head](/head); the `head` of every matched page is used, outermost first                                                             |
| `key`                                | `string \| (route) => string`                    | none                       | run time | the page mounts again when it changes ([Remounting a page](#remounting-a-page))                                                                     |
| `params`                             | `Record<string, StandardSchemaV1>`               | none                       | run time | a schema per param ([Params that are checked](#params-that-are-checked))                                                                            |
| `validate`                           | `(route) => boolean \| HamurError \| Promise<…>` | none                       | run time | `false` answers 404, a returned `HamurError` is thrown                                                                                              |
| `props`                              | `boolean`                                        | `false`                    | run time | `true` passes the route's params as props to the page component                                                                                     |
| `instant`                            | `boolean`                                        | `false`                    | run time | `hamur dev` warns when a navigation to the page waits more than 200 ms with nothing to show ([HAMUR_W1240](/errors/HAMUR_W1240))                    |
| `appRoot`                            | `false`                                          | none                       | run time | `false` renders the page without `app/app.tsx`                                                                                                      |
| `document`                           | `string`                                         | the default document       | run time | `app/documents/<name>.html`, with `<!--hamur-head-->` in `<head>` and `<!--hamur-body-->` in `<body>`; an unknown name is a build warning and a 500 |
| `pageTransition`, `layoutTransition` | `boolean \| PageTransition`                      | `app.*`                    | run time | [Page and layout transitions](/api-reference/navigation-details#page-and-layout-transitions)                                                        |
| `viewTransition`                     | `ViewTransitionOption`                           | `app.viewTransition`       | run time | [View transitions](/api-reference/navigation-details#view-transitions)                                                                              |
| `keepalive`                          | `boolean`                                        | `app.keepalive`            | run time | [Keep-alive](/api-reference/navigation-details#keep-alive)                                                                                          |
| `pendingMs`, `pendingMinMs`          | `number`                                         | `app.navigation.*`         | run time | [the pending state](/api-reference/navigation-details#pending-thresholds-and-the-link-state)                                                        |
| `scrollToTop`                        | `boolean \| (to, from) => boolean`               | `true`                     | run time | [Scroll](/api-reference/navigation-details#scroll)                                                                                                  |
| `path`                               | `string`                                         | the file's pattern         | build    | replaces the path the file gives                                                                                                                    |
| `alias`                              | `string \| string[]`                             | none                       | build    | more paths that serve this page, with its name and params                                                                                           |
| `redirect`                           | `string \| { to; status? }`                      | none                       | build    | answers the page's path with a redirect, 307 unless `status` is 301, 302, 303 or 308                                                                |
| `parents`                            | `boolean`                                        | `true`                     | build    | `false` leaves out the parent pages and group layouts ([Nested routes](#nested-routes))                                                             |
| `rules`                              | `RouteRule`                                      | none                       | build    | a route rule for the page's path ([Configuration](/configuration))                                                                                  |
| `serverOnly`                         | `true`                                           | none                       | build    | the page's code stays out of the client build                                                                                                       |
| `hydrate`                            | `"full" \| "islands"`                            | `"full"`                   | build    | `"islands"` makes an [island page](/islands-and-streaming)                                                                                          |

A child's key replaces its parent's; arrays are not joined. `head` and `middleware` are the exceptions: every matched page's own is used, outermost first. In Vue the export goes in a plain `<script lang="ts">` block next to `<script setup>`, in Svelte in `<script module>`.

### Build keys must be literals

The scanner reads `path`, `alias`, `redirect`, `parents` and `rules` from the source text of `export const meta = { … }`. A literal is a string, a number, `true`, `false`, `null`, or an array or object of literals. An identifier, a call, a spread, a computed key or a template with `${}` is not one.

````tsx [routing/pricing.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>
}
````

| Key                     | Rule                                                                                                                                                                                                       |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `path`, `alias`         | patterns with the page's own params ([HAMUR_E1024](/errors/HAMUR_E1024)). A page with child routes keeps its file path ([HAMUR_E1022](/errors/HAMUR_E1022)). The route has one name whichever path matched |
| `redirect`              | a route rule under the path and each alias; a config or module rule on the same pattern wins. The static presets write it to `_redirects`. Other statuses are [HAMUR_E1054](/errors/HAMUR_E1054)           |
| `redirect` with `rules` | a segment that mixes text and a param cannot be a rule ([HAMUR_E1066](/errors/HAMUR_E1066)), and only one of `meta.redirect` and `meta.rules.redirect` may be set ([HAMUR_E1061](/errors/HAMUR_E1061))     |
| `parents`               | the literal `true` or `false` ([HAMUR_E1049](/errors/HAMUR_E1049))                                                                                                                                         |

`export const meta = base`, `export { meta }` and a key set through a spread give the build nothing. `hamur dev` fails the page when the two values differ: `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 = { … }`.

### Params that are checked

`meta.params` validates each named param with a Standard Schema, and `meta.validate(route)` then decides with the outputs. With `props: true` the component gets them as props.

````tsx [routing/users/[id].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>
}
````

- Both run before any middleware, on the server and in the browser.
- A refusal is a 404 `Page Not Found: <path>`, shown by the not-found component or route boundary that covers the page. `data.issues` is set in development only.
- A [param matcher](#param-matchers) is different: it decides which route a URL is, while these refuse a route that exists.
- A wrong value 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`, or `meta.validate of app/pages/users/[id].tsx must return a boolean or a HamurError (got string)`.

## Remounting a page

A page keeps its state while only its params change: a counter in `/u/1` is still there on `/u/2`. Export `meta.key`, a string or a function of the route, to mount the page again when the value changes:

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

`_template.tsx` in a pages folder wraps every page of that folder, below its layout and parent page. It mounts again whenever the path of the page below it changes: `/t/a` to `/t/b` resets it and the page, `/t/a/x` to `/t/a/y` keeps them.

- It renders `Outlet`, has no `load`, `meta` or error file of its own, and reads `useData()` as `null`.
- Two in one folder are [HAMUR_E1035](/errors/HAMUR_E1035).
- An html page is rendered again on every navigation, so it has no state to reset.

## Route middleware

Route middleware runs on the server for the first request and in the browser for every later navigation. It steers the visitor and guards nothing: the check that must hold belongs in the [handler](/sessions-and-security#protecting-a-page-and-its-data).

| The function                           | What happens                                                                                                                                                                         |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| returns nothing                        | the navigation goes on                                                                                                                                                               |
| returns `redirect(to, status = 302)`   | a redirect. A redirect to the URL being answered is a 500 error that names the loop                                                                                                  |
| returns `false` or `abortNavigation()` | the navigation is cancelled and no later middleware runs. The page and the URL stay. On the server and on the first load of a single-page route it is a 404 `Page Not Found: <path>` |
| throws `createError`                   | the error page or the covering route boundary                                                                                                                                        |

````ts [abort-middleware.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()
})
````

It receives the target route, the route it came from (`undefined` on the server and on the first load) and [`{ state, app, event }`](/api-reference/app#middleware-middlewarecontext). `event` is `undefined` in the browser.

A redirect to another origin needs `{ external: true }`, or the visitor gets an error page. A target that starts with `//` or `\\` counts as another origin, and the scheme must be in [`app.linkProtocols`](/api-reference/navigation-details#link-protocols).

````ts [external-redirect.ts]
import { defineRouteMiddleware, redirect } from "hamur/app"

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

### Where middleware is set

| For                        | Put it in                                                                                                                                                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| one page                   | `meta.middleware` of the page                                                                                                                                                                                            |
| a folder                   | `meta.middleware` of its `_meta.ts`                                                                                                                                                                                      |
| every route                | `app/pages/_meta.ts` of the first `dir.pages` folder. It runs on every route, also one from a layer, a module or `app/routes.ts`; its other keys cover its folder only. A layer's own `app/pages/_meta.ts` does the same |
| every route, at run time   | [`addRouteMiddleware(fn, { app })`](/api-reference/app#addroutemiddleware) in an app plugin                                                                                                                              |
| every route, from a module | `addRouteMiddleware({ path, global: true })` of `hamur/kit`                                                                                                                                                              |
| one side only              | the function returns early: `if (import.meta.server) return`                                                                                                                                                             |

````ts [routing/run-time-middleware.ts]
import { addRouteMiddleware, definePlugin } from "hamur/app"

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

- Nothing scans `app/middleware/`: a file there runs only where it is imported. A name that says global, a side or an order, such as `auth.global.ts`, `track.client.ts` or `01.auth.ts`, fails the scan with [HAMUR_E1246](/errors/HAMUR_E1246).
- A name in `meta.middleware` is a type error, and a 500 at run time: `meta.middleware of app/pages/admin.tsx is the name "auth"; import the middleware and pass the function`.
- While `hamur generate` prerenders, a page whose middleware redirects is skipped with a warning. Give the route `ssr: false` to prerender its shell and run the middleware in the browser.

### The order of the checks

1. The route is matched, with the [param matchers](#param-matchers).
2. The page modules and folder configs load.
3. `meta.params`, then `meta.validate`, of each matched page, parent first.
4. The `search` schemas.
5. Middleware for every route: the modules', then those added at run time, then `app/pages/_meta.ts`, the app's before each layer's.
6. Per page, parent first: its folder configs' middleware, outermost folder first, then its own, each array as written.
7. The `load` files.

Step 5 runs even when a route boundary has taken a failure of step 3 or 4. Step 6 is then left out for the failing route and the routes below it.

## Search params

A page may export `search`, a Standard Schema (what Zod, Valibot and ArkType make) for its query string. Every reader gets the result with defaults filled in: `ctx.search` in a `load`, `to.search` in middleware and `useRoute().search` in a component.

````tsx [forms/app/pages/products.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>
  )
}
````

| Topic                    | Rule                                                                                                                                                                                                             |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| no schema                | `search` equals `query`, or what the `parse` of `app/search.ts` returns                                                                                                                                          |
| an invalid query         | 400 `Invalid search params`, with `data.issues` as `{ path, message }`. `meta.searchError: "strip"` drops the top-level keys the issues name and validates again. The innermost page's value wins                |
| parents                  | they validate first; each schema gets the query, and its output is merged over the earlier ones                                                                                                                  |
| types                    | after `hamur typegen` the schema's output is the type of `search` for that route                                                                                                                                 |
| `useSearch(select?)`     | `{ value, set }`. `set(next, { replace = true })` navigates with that search and runs the guards and the `load` files whose [`searchKeys`](/data#search-keys) changed. `next` may be a function of the old value |
| a selected value         | compared by deep equality, so a component updates only when its part changes                                                                                                                                     |
| without the hook         | `router.navigate({ query: (prev) => next })`, and `query={(prev) => next}` on a `Link`                                                                                                                           |
| defaults                 | a key is left out of the URL when validating without it gives the same value. A query string you write by hand is never changed                                                                                  |
| lists and objects        | a key the schema types as an object, array, number or boolean is written as JSON: `tags=["a","b"]`                                                                                                               |
| `searchRetain = ["tab"]` | a page's export; those keys go to every `Link` and `navigate()` built from that page or its children, unless the target sets them                                                                                |
| Vue and Svelte           | the export goes in the plain `<script lang="ts">` block, or in `<script module>`                                                                                                                                 |

`app/search.ts` replaces how the whole app reads and writes a query. A `parse` that throws gives the same 400.

````ts [api/app-search-codec.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))}` : ""),
})
````

## A route table in code

`app/routes.ts` changes the routes after the scan and after the modules' `pages:extend`. It default-exports a function from the scanned `RouteRecord[]` to the new table.

````ts [routing/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")]),
]
````

- `route(path, file, children?)`, `index(file)`, `group(file, children)` (a pathless layout) and `prefix(path, children)` of `hamur/kit` build records. A path without a leading `/` is relative to its parent's, and `file` to `app/`.
- The records are checked as scanned ones are. A missing file is [HAMUR_E1133](/errors/HAMUR_E1133) and a wrong default export [HAMUR_E1131](/errors/HAMUR_E1131).
- Only the app's own `app/` has a route table; a layer cannot provide one.
- `dir` in `hamur.config.ts` renames `pages`, `layouts` and `middleware`, relative to `app/`. `dir.pages` may be a list; two folders that serve one path fail the build.

## Lazy discovery and server bundles

````ts [routing/hamur.config.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/**"] } },
})
````

`app.routeDiscovery: "lazy"` makes the browser's list of routes smaller:

- The entry keeps the root and the pages that can match any first segment. The others are one file per first segment, `<baseURL><buildAssetsDir>manifest/<build id>/<segment>.json`, cached as immutable.
- The document carries the records of its own segment. A client navigation to another segment loads that file first.
- `hamur dev` ignores the setting.

`build.serverBundles` splits the server build for serverless hosts. A key is a branch id, a value the route-rule patterns of its pages:

- A branch's pages, `load` files and their boundary, template and folder-config modules go to `.output/server/<id>/index.mjs`, which loads on the first request that needs it.
- A page no pattern names stays in the main bundle, with the layouts, handlers and middleware.
- A page in two branches fails the build: `build.serverBundles: /admin/users is in "admin" and "users"`. A branch that names no page is a warning.
