Skip to content

Routing details

The rules, options and build errors behind the Routing guide. .tsx stands for the page extension of your library.

Files and routes

File in app/pages/PathWhat it matches
index.tsx/
blog/[slug].tsx/blog/:sluga required param
users/[[id]].tsx/users/:id?an optional param
docs/[...path].tsx/docs/**:patha 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-:idseveral params in one segment
items/[id=integer].tsx/items/:ida param that passes a matcher
(marketing)/pricing.tsx/pricinga (group) folder adds nothing to the path
[...slug].tsxevery unmatched pathyour own 404 page; it answers 200 unless it throws createError({ status: 404 })
RuleWhat happens
paramsa string, decoded with decodeURIComponent; a catch-all is a string[]. A malformed escape answers 400
best matchcompared segment by segment: static, text mixed with params, a required param, an optional param, a catch-all, an optional catch-all
ignored filesa name that starts with _ or ., except the route conventions; *.test.*, *.spec.* and *.d.ts
two pages, one URLa build error that names both files (HAMUR_E1043)
not HTMLa request that does not prefer HTML and matches no page gets a JSON 404
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.trailingSlashWhat 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.

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), an escaped / (HAMUR_E1005), control character (HAMUR_E1006) or surrogate (HAMUR_E1007), and an optional param beside another param (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.

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 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.
SlipBuild error
a suffix file without its pageHAMUR_E1033
two files of one kindHAMUR_E1034
a name one letter off, such as _eror.tsxHAMUR_E1030
_loading.tsx, the Next.js nameHAMUR_E1038
_layout.tsx, the Remix nameHAMUR_E1039
_meta with a wrong extensionHAMUR_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 }).

QuestionAnswer
what it catcheswhat the route's load, its middleware, meta.params, meta.validate, a search schema or the component's render throws
where it showsin the place of the failing route: a failing dash/broken inside dash, a failing dash inside the layout
what it never catchesa 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 shows those
a 404the covering not-found component wins over a route boundary at any level; without one, the nearest route boundary takes it. Throw notFound() in a load
several failing loadsthe outermost failing route wins and the others are logged
status and hookthe answer has the error's status; page:error runs before the boundary renders
a URL no page matchesapp/pages/_not-found.tsx, inside the root and the default layout. app.notFoundMode: "fuzzy" changes that

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 only (HAMUR_E1119). It has no default export (HAMUR_E1117) and must export meta (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
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.

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
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>
}

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

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 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.
SlipBuild error
dash/@sidebar.tsx, a named view of NuxtHAMUR_E1018
a slot with no page beside its folderHAMUR_E1015
a slot inside a slotHAMUR_E1013
a slot page whose URL no main page servesHAMUR_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
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>
}

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

tsx
export default function ModalClosed() {
  return null
}
PrefixThe 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), the folder is outside a slot (HAMUR_E1016), and (..) goes above / (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. 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 { 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.
  • 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
<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
<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
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
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 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.

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:

OrderWhere
1a setPageLayout call
2meta.layout of the page, its parents or a folder config: a name, false or { name, props }
3appLayout of the matching route rule (Configuration)
4default, when app/layouts/default.tsx exists

Route middleware can choose the 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 give the path segments below it, a group as (group). useOutletContext reads the context of the Outlet above, useResolvedPath resolves .., and useLayout returns the layout's name and props.

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.

KeyTypeDefaultReadMeaning
layoutstring | false | { name; props? }"default" when it existsrun timethe layout
middlewarea function or an array of themnonerun timeroute middleware
ssrboolean | "data-only" | (ctx) => …truerun timefalse renders the page in the browser only; "data-only" runs the loads on the server (Rendering modes)
scriptsfalsenonerun timea 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 timewhat an invalid query does (Search params)
staleTime, gcTimenumberapp.data.*run timethe client data cache of this page
headHeadInputnonerun timethe page's own head; the head of every matched page is used, outermost first
keystring | (route) => stringnonerun timethe page mounts again when it changes (Remounting a page)
paramsRecord<string, StandardSchemaV1>nonerun timea schema per param (Params that are checked)
validate(route) => boolean | HamurError | Promise<…>nonerun timefalse answers 404, a returned HamurError is thrown
propsbooleanfalserun timetrue passes the route's params as props to the page component
instantbooleanfalserun timehamur dev warns when a navigation to the page waits more than 200 ms with nothing to show (HAMUR_W1240)
appRootfalsenonerun timefalse renders the page without app/app.tsx
documentstringthe default documentrun timeapp/documents/<name>.html, with <!--hamur-head--> in <head> and <!--hamur-body--> in <body>; an unknown name is a build warning and a 500
pageTransition, layoutTransitionboolean | PageTransitionapp.*run timePage and layout transitions
viewTransitionViewTransitionOptionapp.viewTransitionrun timeView transitions
keepalivebooleanapp.keepaliverun timeKeep-alive
pendingMs, pendingMinMsnumberapp.navigation.*run timethe pending state
scrollToTopboolean | (to, from) => booleantruerun timeScroll
pathstringthe file's patternbuildreplaces the path the file gives
aliasstring | string[]nonebuildmore paths that serve this page, with its name and params
redirectstring | { to; status? }nonebuildanswers the page's path with a redirect, 307 unless status is 301, 302, 303 or 308
parentsbooleantruebuildfalse leaves out the parent pages and group layouts (Nested routes)
rulesRouteRulenonebuilda route rule for the page's path (Configuration)
serverOnlytruenonebuildthe page's code stays out of the client build
hydrate"full" | "islands""full"build"islands" makes an island page

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
import type { PageMeta } from "hamur/app"

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

export default function Pricing() {
  return <h1>Pricing</h1>
}
KeyRule
path, aliaspatterns with the page's own params (HAMUR_E1024). A page with child routes keeps its file path (HAMUR_E1022). The route has one name whichever path matched
redirecta 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
redirect with rulesa segment that mixes text and a param cannot be a rule (HAMUR_E1066), and only one of meta.redirect and meta.rules.redirect may be set (HAMUR_E1061)
parentsthe literal true or false (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
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 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.
  • 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.

The functionWhat happens
returns nothingthe 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 createErrorthe error page or the covering route boundary
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 }. 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.

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

ForPut it in
one pagemeta.middleware of the page
a foldermeta.middleware of its _meta.ts
every routeapp/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 timeaddRouteMiddleware(fn, { app }) in an app plugin
every route, from a moduleaddRouteMiddleware({ path, global: true }) of hamur/kit
one side onlythe function returns early: if (import.meta.server) return
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.
  • 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.
  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
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>
  )
}
TopicRule
no schemasearch equals query, or what the parse of app/search.ts returns
an invalid query400 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
parentsthey validate first; each schema gets the query, and its output is merged over the earlier ones
typesafter 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 changed. next may be a function of the old value
a selected valuecompared by deep equality, so a component updates only when its part changes
without the hookrouter.navigate({ query: (prev) => next }), and query={(prev) => next} on a Link
defaultsa 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 objectsa 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 Sveltethe 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
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
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 and a wrong default export 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
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.