Skip to content

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

Route rules and prerender

routeRules in hamur.config.ts set how a path is answered: headers, a redirect, a rewrite, a cache, a proxy, and whether it is prerendered. Deploy lists the basic keys and proxy. This page covers the rest: keys with a method, params and conditions, rewrites, the redirects file, what each preset writes, and the prerender that follows from the rules.

Keys

A key is an optional method, a space and a path pattern. The pattern uses the forms of Routing: * and :name for one segment, :name? for a last segment that may be absent, ** and **:name for the rest of the path.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  routeRules: {
    "GET /feed": { headers: { "cache-control": "public, max-age=60" } },
    "/feed": { headers: { "x-feed": "1" } },
    "/blog/:slug": { redirect: "/posts/:slug" },
    "/old/:slug": { redirect: { to: "/new/:slug", status: 308 } },
    "/orders/:id(\\d+)": { rewrite: "/order/:id" },
    "/guide/:lang?": { headers: { "x-guide": "1" } },
    "/files/**:path": { rewrite: "/assets/**" },
  },
});
FormMeaning
GET /feedapplies to GET requests, and to HEAD as a GET server route answers it; HEAD /feed applies to HEAD only. The method is upper case, one of GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, then one space
/blog/:slug:slug captures one segment; a target can use it
/guide/:lang?matches /guide and /guide/de; only the last segment can be optional
/files/**:path** that is named; zero or more segments
/orders/:id(\d+)one segment whose decoded text matches the expression as a whole; the expression has no flags and no /. In a TypeScript string the backslash is doubled, as in the sample

A name appears once in a key, and a segment cannot mix text and a param (/shop/:a-:b fails the build). The most specific key wins where several match. From least to most specific: a ** before none, then more static segments, then more constrained segments, then fewer unconstrained single segments, then more segments. At an equal pattern the key with a method ranks after the one without, so GET /feed wins over /feed, and /feed over GET /**. Rules from all matching keys merge, the most specific value last.

A key that is not valid fails when the config loads: routeRules key "get /feed": the method is upper case, one of GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, then one space, or Route rule pattern "/a/:x?/b" may use an optional param only as its last segment.

Targets

A redirect, rewrite or proxy target can use what the key matched:

  • ** is what ** (or **:name) matched.
  • :name is the key's param of that name, or a capture of the entry that applied (see Conditions). A name the key does not define fails the build: routeRules["/a/:x"].redirect uses :y, which the key does not define.
  • Values go in as the request had them, percent-encoded. A value with an empty segment before the last, a . or .. segment, or a backslash answers 400. An absent :name? drops its segment with the /.
  • A target with ** or a :name keeps the request's query when it has no ? of its own, so /blog/a?x=1 goes to /posts/a?x=1. A literal target drops it.
  • A :name inside the host of an absolute target is text, never a param: write the host out.

Redirect status

redirect takes a string or { to, status }. The status is 307 unless you give one. There is no permanent key: write status: 308 (or 301). { to, permanent: true } fails at load with routeRules["/a"].redirect has no key "permanent"; write status: 308.

Rewrites

A rewrite answers a request with another page of the app while the address bar keeps the URL. The rule rewrite takes an app path: / and then the path, no scheme. ** and :name are filled in as for a redirect, and the query is the request's with the target's own keys set over it. The target can be a page, a handler route or a file in public/. The answer's status is the target's. A rewrite never leaves the app: Route rule "/a" rewrite: rewrite target must be an app path; use a proxy rule for https://example.com/x.

In the target useRoute() is the target's route, and useRoute().mask is the path in the address bar. A rewrite to a path already visited in the request, or a sixth one in a row, is the error Rewrite loop: /a → /b → /a, with status 508 on the server and 500 in the browser.

Three places start a rewrite:

  • A rule. rewrite in routeRules. The browser applies a rule without a condition to its own navigations too, so a link to the source renders the target without a document request. A rule with a condition or a regex constraint is a full load, and the server decides.
  • Code. return rewrite("/login", { status: 401 }) from route middleware or a load (rewrite), and from a request step of the server (Server).
  • The reroute file. app/reroute.ts maps URLs to app paths in code, on the server and in the browser.
ts
const slugs: Record<string, string> = { "/de/ueber-uns": "/about", "/fr/a-propos": "/about" };

export function input(url: URL): string | undefined {
  return slugs[url.pathname];
}

export function output(url: URL): string | undefined {
  const match = /^\/tenants\/[^/]+(\/.*)$/.exec(url.pathname);
  if (match) return match[1] + url.search;
}

input(url) gets the URL asked for and returns an app path, a URL on the same origin, or nothing. The server runs it once per request, after the redirects file and the redirect rules; the browser runs it before it matches each navigation and keeps an asynchronous answer for the life of the page. A result that differs from the path is a rewrite. output(url) is synchronous: it gets an app path and returns the URL to show, and Link, navigate, replace and prefetch apply it. An app with an output also writes the input that maps the shown URL back, since a reload asks the server for it. The file exports input, output or both; an export of any other name fails the build, and an input that returns another origin throws app/reroute.ts input returned https://other.example/x, which is not on this origin.

Conditions

A key's value can be a list of entries. Each entry is a rule and may have when. The first entry whose has conditions all hold and whose missing conditions none do is the rule of that key for the request. An entry without when always applies, so put it last. When no entry applies, the key adds nothing.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  routeRules: {
    "/": [
      { when: { has: [{ type: "cookie", key: "bucket", value: "b" }] }, rewrite: "/home-b" },
      { when: { has: [{ type: "host", value: "(?<tenant>[a-z]+)\\.example\\.com" }] }, rewrite: "/tenants/:tenant" },
      { headers: { "x-home": "default" } },
    ],
    "GET /docs/**": [{ when: { has: [{ type: "header", key: "x-beta" }], missing: [{ type: "query", key: "stable" }] }, rewrite: "/guide/**" }],
  },
});
ConditionHolds when
{ type: "header", key, value? }the request header is present and, with value, its whole value matches
{ type: "cookie", key, value? }the cookie is present and, with value, its decoded value matches
{ type: "query", key, value? }the search param is present and, with value, one of its values matches
{ type: "host", value }the host (the forwarded host under server.trustProxy), without the port and in lower case, matches

value is a regular expression source matched as a whole. A named group in it, such as (?<tenant>[a-z]+), is a param for the targets of that entry.

  • An entry under when takes redirect, rewrite, proxy, headers, noindex, swr, cache and ssr. The other keys are read at build or by the client, where no request exists, and fail the build: routeRules["/x"][0] sets prerender under when; a conditional entry takes redirect, rewrite, proxy, headers, noindex, swr, cache and ssr.
  • No entry of a list takes basicAuth, ipRestriction, rateLimit or cors, because the fallback entry applies only when no earlier one does. Put them on a key whose value is a rule, and the conditional entries on a method key.
  • A cached rule varies on every header its conditions test (cookie for a cookie condition), and the answer gets a Vary with them.
  • When the config, a module and a page's meta.rules set the same key, a list is kept whole if it is the first value set, and a list that comes after a rule is dropped and the rules merge. If another source of the key sets basicAuth, ipRestriction or rateLimit that a kept list would drop, the build fails.

The redirects file

For many exact redirects, such as the old URLs of a site, list them in a file instead of writing a rule for each. Set redirects to a .json or .csv file, a path from the project root.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  redirects: "redirects.json",
});

JSON is an array of { from, to, status? }:

json
[
  { "from": "/about-us", "to": "/about", "status": 301 },
  { "from": "/jobs", "to": "https://jobs.example.com/" }
]

CSV has a header line from,to or from,to,status, then one entry a line. A field may be in double quotes, "" is a quote inside one, and empty lines are skipped.

csv
from,to,status
/about-us,/about,301
/jobs,https://jobs.example.com/,307
  • status is 301, 302, 307 or 308, and 307 when absent.
  • from is an exact app path below app.baseURL, with no *, :, ? or #. It is compared as a rule path is: segments decoded, one trailing / dropped, lower case under app.caseSensitive: false.
  • to is an app path or an http(s) URL, without ** or :name. The request's query is dropped.
  • The file is read when the config loads, and again by hamur dev when you save it, without a restart.
  • It is answered before every route rule. Static files and the access rules come first, as for every redirect.
  • A from that is also a file of .output/public/ fails the build after the prerender, because the file would answer first: redirects.json: "/about" is also the file public/about/index.html, which answers before a redirect.
MistakeMessage
another extensionredirects must name a .json or .csv file (got "redirects.txt")
a bad headerredirects.csv line 1: the header must be from,to or from,to,status
a pattern in fromredirects.csv line 4: from "/blog/*" is not an exact path; use routeRules for patterns
a bad statusredirects.csv line 4: status 304 is not a redirect status; use 301, 302, 307 or 308
a repeatredirects.json: "/a" is listed twice (entries 4 and 9)

Order of a request

  1. The request hook.
  2. ipRestriction and basicAuth, then static files.
  3. The CORS preflight, rateLimit, bodyLimit and timeout, then the origin check.
  4. The redirects file.
  5. The rule redirect.
  6. The reroute file's input.
  7. The rule rewrite.
  8. The rule proxy.
  9. The middleware list of defineServer.
  10. Handler routes, then pages.

A rewrite starts the request again as a request for the target, a target pass. The pass runs the access rules, static files and origin check for the target, with the target's bodyLimit, then its rewrite and proxy rules, the request steps not entered yet, and the target's route or page. It skips the request hook, the preflight, rateLimit, timeout, the redirects, and the case and trailing-slash redirects.

What each preset writes

A server preset (bun, node) applies every rule itself. On the others the build also writes the platform's files for the keys they can carry, and the function applies the rest.

Keybun, nodevercelnetlify, cloudflarestatic
headers, noindexthe serverroutes in config.json_headers_headers
redirectthe serverthe function_redirects_redirects
rewrite, a literal onethe serverthe functionthe functiona _redirects line <from> <to> 200; each exact source is also written as the target's page
a method key, a condition, a regex constraintthe servera condition's headers and noindex become config.json routes with has/missing where the entries allow it; the rest the functionthe functiondropped, and listed
the redirects filethe serverthe function_redirects lines (on cloudflare up to the static budget)_redirects lines and a redirect page for each from
proxy, cors, swr, cachethe serverthe functionthe functiondropped, and listed
basicAuth, ipRestriction, rateLimit, bodyLimit, timeout, originCheckthe serverthe functionthe functionbasicAuth and ipRestriction fail the build; rateLimit is ignored with a warning; the others need a server
prerender, ssr, appLayout, appMiddlewareread at build, and by the client for the last twosamesamesame
  • Named params go into the platform files as the platform writes them: :name for :name, * and :splat for **:name. A regex constraint cannot be written there: the function answers it.
  • Headers and notices for a key the platform cannot carry. On vercel, netlify and cloudflare the function applies the headers of a method key or a condition, but files the platform serves under it do not get them. The build warns once for each key: Route rule "GET /feed" headers are matched by the function only (method key): files the netlify platform serves under it do not get them. The static build lists them in its warning, route rule "GET /feed" headers (method key), with (condition) or (regex constraint) for the others.
  • _redirects has the app's own public/_redirects lines first, then # Generated by Hamur, the redirects file, then the rule lines. A redirect that a basicAuth or ipRestriction key may cover is left out of the file on netlify and cloudflare, since the platform answers that file before the function checks access, and one warning names it.
  • On cloudflare the redirects file fills what is left of the 2000 static rules that Cloudflare reads. The worker answers the other entries, and the build logs redirects: 1840 of 10000 entries are in _redirects (Cloudflare reads 2000 static redirects); the worker answers the other 8160.

Reading rules in code

getRouteRules(event) returns the merged rule of the request that is running. getRouteRules({ method?, path, headers? }) returns it for a request that was not made, from the table of the running app, and matchRouteRules(routeRules, { path }) does the same for a table you pass, without a running app. That one is what a test calls. See getRouteRules and matchRouteRules.

Prerender

hamur generate runs the built server in process and writes what it answers for each seed path, and hamur build does the same on every preset for the paths a rule, entries or prerender.routes names. The seeds are, in this order:

  1. On the static preset, / and every page path without params.
  2. With prerender.staticPages: true, every page path without params whose layouts, parents and page have no load.
  3. Rule patterns with prerender: true (a pattern with a param is not a path), and pages with meta.rules: { prerender: true }.
  4. Page entries of every dynamic page, on every preset.
  5. prerender.routes.
  6. On the static preset, every from of the redirects file and every exact source of a literal rewrite rule.
  7. The prerender:routes hook.

prerender: false and prerender.ignore leave a path out whatever seeds it. After the crawl one line lists them, Prerender left out 3 paths (prerender: false or prerender.ignore): /admin, /admin/users, /dash; on the static preset the host answers them with 404.html, and that is not an error.

prerender.routes as a function

prerender.routes is a list of paths, or a function called once at build with every page path without params, sorted. Under ssr: false a path it lists is written as a full page and every other path keeps the shell.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  prerender: {
    routes: ({ staticPaths }) => staticPaths.filter((path) => !path.startsWith("/internal")),
    onMissingId: "fail",
    onUnseenRoutes: "warn",
    errorPages: [404, 500],
    sharedData: true,
  },
});

The result must be an array of paths that start with /: prerender.routes() returned "about"; each path starts with "/".

Reports after the crawl

  • Unseen routes. A page marked for prerender (on the static preset every page, elsewhere a page with prerender: true) that no written path matched is reported once: Prerender wrote no path for routes marked for prerender: /blog/:slug (app/pages/blog/[slug].tsx); give them entries, link to them, or set prerender.onUnseenRoutes: "ignore". prerender.onUnseenRoutes is "warn" (the default), "fail" or "ignore". "fail" ends hamur build and hamur generate with exit code 1 whatever failOnError says.
  • Missing ids. A crawled link /about#team to a written page that has no element with id="team" or <a name="team"> is reported as / links to /about#nope, but /about has no element with id "nope". prerender.onMissingId is "warn", "fail" or "ignore". An empty fragment and #top always pass.
  • On-demand pages. A build on a server preset with no prerender logs 12 prerendered, 3 on demand: the 2xx HTML pages written, and the page routes the server renders on request.

Shared data

With prerender.sharedData on (the default), a value that is the same request on every page runs once in the build: a call of a GET handler with the same input, and a useFetch GET whose key Hamur derived from the URL. Every page gets its own copy. A call is not shared when it fails, calls taint(), changes the status, a header or a cookie, or returns a value that would not come back as it was. A key you chose with useAsyncData(key, …) or useFetch(url, { key }) is never shared. A GET handler that reads the request URL to answer shares the first page's answer, so set sharedData: false for such an app.

Error pages

The static preset writes <status>.html for each status in prerender.errorPages, each the app's error page rendered for that status. The default [404] writes 404.html; true is the same and false writes none. A status outside 400 to 599 is left out with prerender.errorPages: 302 is not an error status; it is left out. A preset that is not static logs once that the server renders its error pages.

Redirect pages

On the static preset a redirect is a page. A rule, a load or the redirects file that redirects is written as an HTML page with a meta refresh. A middleware redirect is skipped with a warning, because the build has no session. Put your own component in app/redirect.<ext> to replace the built-in page:

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

export default function Redirect({ from, to, status }: { from: string; to: string; status: 301 | 302 | 303 | 307 | 308 }) {
  useHead({ meta: [{ "http-equiv": "refresh", content: `0; url=${to}` }] });
  return (
    <main data-from={from}>
      <h1>{`Moved (${status})`}</h1>
      <a href={to}>{to}</a>
    </main>
  );
}

It is the whole page of the document: no layout, no app root and no client script, and it never hydrates. Its props are from, to and status. It sets its own refresh, and a written page without a <meta http-equiv="refresh"> that has url=<to> fails the build: app/redirect must render a meta refresh to /new (for /old).

Paths found while rendering

prerenderRoutes(...paths) from hamur/app queues paths from a page, a load, route middleware or a plugin while the server renders a prerender request. A handler uses prerenderRoutes(event, ...paths) from hamur/server. The paths are followed like links, so prerender.ignore and prerender: false apply. In the browser and outside a prerender both do nothing. See prerenderRoutes.

A route that is not a page

A server route answers a path with data, a file or a stream, with no page. defineHandler({ route, raw: true }) gives it a URL, and the route rules apply to that URL like any other.

ts
import { defineHandler, getRouterParam } from "hamur/server";

export const reportCsv = defineHandler({
  route: "/reports/:id/export",
  method: "GET",
  raw: true,
  handler(_, { event }) {
    const id = getRouterParam(event, "id") as string;
    return new Response(`id,total\n${id},42\n`, { headers: { "content-type": "text/csv; charset=utf-8" } });
  },
});