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.
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/**" },
},
});
| Form | Meaning |
|---|---|
GET /feed | applies 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.:nameis 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:namekeeps the request's query when it has no?of its own, so/blog/a?x=1goes to/posts/a?x=1. A literal target drops it. - A
:nameinside 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.
rewriteinrouteRules. 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 aload(rewrite), and from a request step of the server (Server). - The reroute file.
app/reroute.tsmaps URLs to app paths in code, on the server and in the browser.
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.
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/**" }],
},
});
| Condition | Holds 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
whentakesredirect,rewrite,proxy,headers,noindex,swr,cacheandssr. 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,rateLimitorcors, 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 (
cookiefor a cookie condition), and the answer gets aVarywith them. - When the config, a module and a page's
meta.rulesset 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 setsbasicAuth,ipRestrictionorrateLimitthat 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.
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
redirects: "redirects.json",
});
JSON is an array of { from, to, status? }:
[
{ "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.
from,to,status
/about-us,/about,301
/jobs,https://jobs.example.com/,307
statusis 301, 302, 307 or 308, and 307 when absent.fromis an exact app path belowapp.baseURL, with no*,:,?or#. It is compared as a rule path is: segments decoded, one trailing/dropped, lower case underapp.caseSensitive: false.tois an app path or anhttp(s)URL, without**or:name. The request's query is dropped.- The file is read when the config loads, and again by
hamur devwhen 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
fromthat 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.
| Mistake | Message |
|---|---|
| another extension | redirects must name a .json or .csv file (got "redirects.txt") |
| a bad header | redirects.csv line 1: the header must be from,to or from,to,status |
a pattern in from | redirects.csv line 4: from "/blog/*" is not an exact path; use routeRules for patterns |
| a bad status | redirects.csv line 4: status 304 is not a redirect status; use 301, 302, 307 or 308 |
| a repeat | redirects.json: "/a" is listed twice (entries 4 and 9) |
Order of a request
- The
requesthook. ipRestrictionandbasicAuth, then static files.- The CORS preflight,
rateLimit,bodyLimitandtimeout, then the origin check. - The redirects file.
- The rule
redirect. - The reroute file's
input. - The rule
rewrite. - The rule
proxy. - The
middlewarelist ofdefineServer. - 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.
| Key | bun, node | vercel | netlify, cloudflare | static |
|---|---|---|---|---|
headers, noindex | the server | routes in config.json | _headers | _headers |
redirect | the server | the function | _redirects | _redirects |
rewrite, a literal one | the server | the function | the function | a _redirects line <from> <to> 200; each exact source is also written as the target's page |
| a method key, a condition, a regex constraint | the server | a condition's headers and noindex become config.json routes with has/missing where the entries allow it; the rest the function | the function | dropped, and listed |
| the redirects file | the server | the function | _redirects lines (on cloudflare up to the static budget) | _redirects lines and a redirect page for each from |
proxy, cors, swr, cache | the server | the function | the function | dropped, and listed |
basicAuth, ipRestriction, rateLimit, bodyLimit, timeout, originCheck | the server | the function | the function | basicAuth and ipRestriction fail the build; rateLimit is ignored with a warning; the others need a server |
prerender, ssr, appLayout, appMiddleware | read at build, and by the client for the last two | same | same | same |
- Named params go into the platform files as the platform writes them:
:namefor:name,*and:splatfor**:name. A regex constraint cannot be written there: the function answers it. - Headers and notices for a key the platform cannot carry. On
vercel,netlifyandcloudflarethe function applies theheadersof 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.Thestaticbuild lists them in its warning,route rule "GET /feed" headers (method key), with(condition)or(regex constraint)for the others. _redirectshas the app's ownpublic/_redirectslines first, then# Generated by Hamur, the redirects file, then the rule lines. A redirect that abasicAuthoripRestrictionkey may cover is left out of the file onnetlifyandcloudflare, since the platform answers that file before the function checks access, and one warning names it.- On
cloudflarethe redirects file fills what is left of the 2000 static rules that Cloudflare reads. The worker answers the other entries, and the build logsredirects: 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:
- On the
staticpreset,/and every page path without params. - With
prerender.staticPages: true, every page path without params whose layouts, parents and page have noload. - Rule patterns with
prerender: true(a pattern with a param is not a path), and pages withmeta.rules: { prerender: true }. - Page
entriesof every dynamic page, on every preset. prerender.routes.- On the
staticpreset, everyfromof the redirects file and every exact source of a literalrewriterule. - The
prerender:routeshook.
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.
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
staticpreset every page, elsewhere a page withprerender: 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.onUnseenRoutesis"warn"(the default),"fail"or"ignore"."fail"endshamur buildandhamur generatewith exit code 1 whateverfailOnErrorsays. - Missing ids. A crawled link
/about#teamto a written page that has no element withid="team"or<a name="team">is reported as/ links to /about#nope, but /about has no element with id "nope".prerender.onMissingIdis"warn","fail"or"ignore". An empty fragment and#topalways pass. - On-demand pages. A build on a server preset with no
prerenderlogs12 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:
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.
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" } });
},
});