hamur
import { defineConfig } from "hamur" is for hamur.config.ts. The config guide is Configuration; this page lists the exports.
defineConfig
Returns the config unchanged. It exists so the editor checks the keys.
function defineConfig(config: HamurConfig): HamurConfig
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
app: { baseURL: "/", head: { titleTemplate: "%s · Shop" } },
runtimeConfig: { apiSecret: "", public: { apiBase: "/api" } },
routeRules: { "/blog/**": { prerender: true } },
});
defineEnv
The default export of app/env.ts: returns the entries unchanged, typed. Each key is a variable name; the build reads the names, public and static from the file's text, so the object is written out as a literal.
function defineEnv<const T extends EnvSchema>(env: T): T
#hamur/env/private exports every name (server code only; client code that imports it fails the build), #hamur/env/public the public names that are not static, and a static name is read as import.meta.env.<NAME>, written into both bundles at build. Values are validated when the server starts (static ones when the build starts); a failure stops with Invalid environment variables: and one line per bad name, a private value reported only by its length.
// app/env.ts
import { defineEnv } from "hamur";
export default defineEnv({
API_KEY: {},
PORT: { schema: (raw) => Number(raw), default: "3000", description: "Port of the HTTP server" },
GA_ID: { public: true },
SHOW_DEBUG: { public: true, static: true, schema: (raw) => raw === "true", default: "false" },
});
EnvEntry, EnvSchema, EnvOutput
EnvEntry is one variable: { public?: boolean; static?: boolean; schema?: StandardSchemaV1 | ((raw: string | undefined) => unknown); default?: string; description?: string }. schema is a Standard Schema or a function that returns the value or throws; default replaces an unset value, not an empty one; static needs public. EnvSchema is Record<string, EnvEntry>. EnvOutput<E> is the type a variable reads as: the schema's output, the function's return type, else string.
HamurConfig, HamurConfigBlock, ResolvedConfig
HamurConfigBlock is the type of an env override block ($development, $production, $test, $env.<mode>): a HamurConfig without rootDir, extends, dev and the block keys.
HamurConfig is what you write: every key is optional. ResolvedConfig is what Hamur reads after it merged your file, the layers in extends and the defaults: every key is set, paths are absolute, and layers is added. Modules and the build see the resolved one as hamur.options.
| Key | Type |
|---|---|
rootDir, srcDir, serverDir, publicDir, buildDir, outputDir | string |
dir | { pages?: string | string[]; layouts?: string; middleware?: string }, folders relative to srcDir (defaults pages, layouts, middleware); ResolvedConfig.dir.pages is always a list. Every folder of pages is scanned, in its own tree; two of them serving one path, or two routes with one name, fail the build naming both files (Duplicate route /about: …/app/pages/about.tsx and …/app/admin-pages/about.tsx). Layers read the same folder names. A value that is not a folder name fails the load (dir.pages must be a folder name or a non-empty array of folder names (got 3), dir.layouts must be a folder name (got ""), dir.pages lists "pages" twice, dir.views is not an option) |
framework | "react" | "vue" | "preact" | "svelte" | "solid" | "html" | (string & {}); any other string is a third-party @hamur/adapter-<id> adapter |
preset | "bun" | "node" | "static" | "cloudflare" | "vercel" | "netlify" | (string & {}); any other string is a third-party preset |
ssr, dev, components | boolean |
app | { baseURL?, buildAssetsDir?, head?, rootId?, trailingSlash?: "ignore" | "redirect" | "always" | "strict", caseSensitive?: boolean, history?: "browser" | "hash", routeDiscovery?: "initial" | "lazy", notFoundMode?: "root" | "fuzzy", scripts?: boolean, crossOrigin?: "anonymous" | "use-credentials" | false, speculationRules?: false | { prefetch?: Eagerness | false; prerender?: Eagerness | false } } (Eagerness is "conservative" | "moderate" | "eager" | "immediate"); speculationRules (default false) writes one <script type="speculationrules"> after the import map of every page document, with the request's nonce, and its hash in the policy of a hash document: a document without a client (scripts: false, or a page with meta.scripts: false) speculates every link below baseURL, a document with a client only its a[data-hamur-reload] and a[rel~="external"] links (the navigator renders every other page link in place), and neither ever <baseURL>_hamur/*, a GET server route, a public file, a proxy, redirect or rewrite rule's paths, a path whose route rule sets speculation: false or a link with data-hamur-prefetch="none"; a speculative request runs middleware and load with the user's cookies and carries Sec-Purpose: prefetch (;prerender when prerendered), so a page whose GET has a side effect sets speculation: false; notFoundMode (default "root") says what answers a URL no page matches: app/pages/_not-found.<ext> inside the default layout with 404, else the app error page; "fuzzy" first renders the deepest parent page whose path is a prefix of the URL, with the not-found component covering its children in its Outlet; scripts: false ships no JavaScript and needs the html adapter; crossOrigin (default false, "anonymous" with build.sri) writes crossorigin on the entry script, modulepreload and stylesheet links; caseSensitive: false (default true) matches pages in any case and answers a page request with capitals by a 301 to its lower-case path; history: "hash" (default "browser") keeps the app path in location.hash (#/about) and needs ssr: false; routeDiscovery: "lazy" (default "initial") keeps only the root and the pages under a dynamic first segment in the client entry and writes the other route records as one file per first path segment, <baseURL><buildAssetsDir>manifest/<build id>/<segment>.json, whose records of the document's segment the payload carries (ignored by hamur dev and with scripts: false) |
runtimeConfig | { public?: Record<string, unknown>; [key: string]: unknown } |
appConfig | Record<string, unknown> |
routeRules | Record<string, RouteRule | RuleEntry[]>; a key "<METHOD> <pattern>" (upper-case method, one space) applies to that method only, GET also to HEAD, and wins over the method-less key of the same pattern. A list holds { when?: { has?, missing? }, …rule } entries, and the first whose conditions hold is the key's rule: a condition is { type: "header" | "cookie" | "query", key, value? } or { type: "host", value }, value a regular expression matched against the whole value. An entry under when takes only redirect, rewrite, proxy, headers, noindex, swr, cache and ssr, and no entry of a list takes basicAuth, ipRestriction, rateLimit or cors, which go on a method-less key whose value is a rule; a cached rule varies on the headers the conditions of its path test. The static preset leaves method keys and conditional rules out of _headers and _redirects and lists them in its warning; vercel writes conditional headers as config.json routes with has/missing |
redirects | string; a .json or .csv file of exact-path redirects, a path from the project root: Array<{ from, to, status?: 301 | 302 | 307 | 308 }>, or a CSV with the header from,to or from,to,status. Answered before every route rule; see Route rules |
modules | a list of a path or package name, a defineModule result, a setup function, or [entry, options] |
storage | Record<string, { driver: string; [option: string]: unknown }> |
devStorage | Record<string, { driver: string; [option: string]: unknown }>; mounts that replace the storage mounts of the same name under hamur dev and while the build prerenders, after $development.storage is applied; the build still bundles the drivers of storage |
server | { trustProxy?: boolean; maxBodySize?: number; maxRequestBodySize?: number; asyncContext?: boolean; openapi?: boolean | OpenAPIConfig; graphql?: boolean | GraphQLConfig }; maxBodySize (default 1 MiB) limits a request body read by a handler, readBody and readFormData; a handler's form.maxBodySize replaces it for that handler (Handlers); asyncContext (default true) runs every request inside the request context so useEvent() finds it, false leaves the context to tracing alone (useEvent) |
prerender | { routes?, crawl?, ignore?, failOnError?, concurrency?, conflict?, staticPages?, onMissingId?, onUnseenRoutes?, sharedData?, errorPages? } |
build | { minify?, sourcemap?: "none" | "linked" | "external", define?, plugins?: BunPlugin[], external?, compressPublic?: boolean | { gzip?, brotli?, zstd? }, assetsInlineLimit?: number, importProtection?: { client?: { deny?: Array<string | RegExp> }; server?: { deny?: Array<string | RegExp> } }, keyedComposables?: KeyedComposable[], envPrefix?: string | string[], sri?: "sha256" | "sha384" | "sha512" | false, serverBundles?: Record<string, string[]> }; serverBundles (default {}) groups pages into server bundle branches, each key a branch id (/^[a-z][a-z0-9-]*$/) and each value route-rule patterns matched against the page patterns: hamur build writes each branch's pages, load files and their boundary, template and folder-config modules to .output/server/<id>/index.mjs, which the main entry imports on the branch's first request, and .output/server/bundles.json ({ "<page pattern>": "<id>" }); handlers, middleware and pages no pattern names stay in the main bundle, a page two branches name fails the build (build.serverBundles: /admin/users is in "admin" and "users") and a branch that names no page logs build.serverBundles.<id> names no page; sri (default false, "sha384" under server.csp in hash or auto mode with strictDynamic on, where false fails at load) writes integrity on the entry script, modulepreload and stylesheet links and in the import map; envPrefix (default ["HAMUR_PUBLIC_"]) names the variables, read when the build starts, that become keys of import.meta.env in both bundles beside MODE, DEV, PROD, SSR and BASE_URL, and "" is refused; keyedComposables lists { name, source, argumentLength } entries the build gives a key, in addition to the adapter's useState (2), useAsyncData (3) and useLazyAsyncData (3) (KeyedComposable) |
imports | { autoImport?: boolean; dirs?: string[] } |
extends | string[] |
node | { requestTimeout?: number; headersTimeout?: number; maxConnections?: number }; limits of the server the node preset starts: requestTimeout ms a request may take to arrive (0 = no timeout, default 300000), headersTimeout ms for its headers (default 66000, or requestTimeout when that is smaller; not above requestTimeout), maxConnections a positive integer (default no cap) |
vercel | { functions?: { maxDuration?: number; memory?: number; regions?: string[]; [key: string]: unknown } }; functions is merged into the function's .vc-config.json, where runtime, handler, launcherType, shouldAddHelpers and supportsResponseStreaming keep the preset's values; functions must be an object |
netlify | { functions?: { region?: string; memory?: number | string; vcpu?: number; [key: string]: unknown } }; functions is merged into the function's config in server.mjs, where path and preferStatic keep the preset's values; functions must be an object |
cloudflare | { env?: string, bindings?: Record<string, { id?: string }> }; env is the wrangler environment whose env.<name> block of wrangler.json(c) the cloudflare build copies into the top level of .output/wrangler.json; an unknown name fails the build, and it must be a non-empty string. bindings gives, by binding name, the id of the D1 database, R2 bucket (its name) or KV namespace that @hamur/db, @hamur/blob or a cloudflare-kv or cloudflare-r2 storage mount binds; env HAMUR_CF_<NAME>_ID is the fallback, and the build writes the d1_databases, r2_buckets or kv_namespaces entry into .output/wrangler.json unless the app's wrangler config declares the binding. A value that is not an object of { id } objects with a non-empty string id fails the load (cloudflare.bindings.DB.id must be a non-empty string (got "")) |
scheduledTasks | Record<string, TaskName | TaskName[]>: a cron expression, always in UTC, to the tasks it runs one after another, each with payload undefined and ctx.scheduledTime, ctx.cron set; five fields (minute hour day month weekday) with *, numbers, ranges, steps after * or a range, lists and the names JAN–DEC, SUN–SAT (0 and 7 are Sunday), or @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly; when both day fields are restricted, a day matches when either does. A bad expression, six fields, a date that never comes (0 0 30 2 *) or an unknown task name fails the build naming it; the bun and node presets run schedules (Bun.cron and a timer), vercel writes Cron Jobs that call <baseURL>_hamur/cron (answered only with authorization: Bearer <CRON_SECRET>; 404 and one error log without CRON_SECRET, 401 with a wrong one) netlify writes one scheduled function per expression and cloudflare writes triggers.crons to .output/wrangler.json (weekday names, 0 9 * * 1 as 0 9 * * MON, since Cloudflare reads 1 as Sunday) and runs them from the worker's scheduled handler, any other preset fails the build, and on bun and node each process runs them, so several replicas run a task several times; a platform may also deliver one cron call twice, so write scheduled tasks to be idempotent |
tasks | { http?: { token: { runtimeConfig: string } }, runOnStart?: TaskName[], queue?: { name: string, binding?: string } }. queue is where enqueue sends on cloudflare: name is the Cloudflare queue (a-z, 0-9, _ and -, at most 63 characters, else tasks.queue.name must be a queue name of a-z, 0-9, _ and - (got "Jobs")), binding its producer binding (default TASKS_QUEUE), which the build adds to .output/wrangler.json as queues.producers unless the app's wrangler config declares that binding (a declared producer sending to another queue fails the build: tasks.queue.name is "jobs", but the app's wrangler config sends the TASKS_QUEUE producer to queue "jobs-staging"; set tasks.queue.name to the same queue, or remove that producer), and { queue: name } to queues.consumers unless the app lists that queue: the worker's queue handler runs each message's task and acks the message when it resolved or retries it when it threw (Cloudflare's retries and dead-letter queue then apply). On vercel name is the Vercel Queues topic: enqueue publishes to it, and the build writes the private consumer function .vercel/output/functions/_hamur/vercel/queue.func with the trigger { type: "queue/v2beta", topic: name }, which runs each message's task and leaves a message whose task threw for Vercel to deliver again (Vercel Queues is a beta feature logs at build); another preset logs tasks.queue is used on the cloudflare and vercel presets only at build. http (off by default) serves POST <baseURL>_hamur/tasks/<name> in a build: a JSON body { payload? } runs the task and answers { result } (500 Task "x" returned a value JSON cannot hold for a Map, a bigint …); the request needs authorization: Bearer <token>, compared in constant time with the runtime config key the option names (HAMUR_<KEY> overrides it), else 401 with www-authenticate: Bearer; an unknown task is 404 only after the token passed; a runtime value unset or under 32 characters answers 503 Task endpoint is not configured and logs once at error. A literal token fails the load: tasks.http.token must be { runtimeConfig: "<key>" }; a token in the config file ends up in the repository. runOnStart (default []) runs those tasks once, in order, with payload undefined, after the server plugins and before a bun or node server listens; under hamur dev once per start of the dev server, not on a hot rebuild; on static once in the build, before the prerender. A failure logs at error and reaches task:error, and the server keeps running; vercel, netlify and cloudflare fail the build (run the task with hamur task run --prod from the deploy step, or through tasks.http on cloudflare). An unknown task name fails the build. hamur task list [root] prints each task with its description and schedules; hamur task run <name> [--payload '<json>'] [--prod] [--port <n>] [root] runs one through a running hamur dev of the same root (GET/POST <baseURL>_hamur/tasks[/<name>], dev only), else in process with the dev config, or with --prod on Bun with the production config, and prints the result as one line of JSON |
devServer | { port?, host?, https?: { key, cert, ca?, passphrase? }, allowedHosts?, prefetch?: boolean, tasks?: boolean, handlers?: Array<{ route, handler }> } (handlers, default []: dev-only request handlers; route starts with / and is a path prefix below app.baseURL, matched on a segment boundary; handler is a file path, relative to the app root even when a layer declares it, whose default export is `(request: Request) => Response |
alias | Record<string, string>; the defaults are ~ and @ (the srcDir) and #shared. #server is not an alias: import … from "#server" reads the door of the root that holds the importing file, server/index.ts, and #server/<name> a layer's or a module's door, in a door file only; a path below it, such as #server/posts/q, resolves in neither the build nor tsc (see Handlers) |
typescript | { strict?: boolean; tsConfig?: Record<string, unknown>; typedPaths?: boolean }; strict (default true) is compilerOptions.strict and tsConfig is merged over the compilerOptions of .hamur/tsconfig.json and the four context files (typescript.strict must be a boolean, typescript.tsConfig must be an object); typedPaths: false types Link to, navigate() and redirect() targets string |
hooks | { [name in keyof HamurHooks]?: HamurHooks[name] }: the build hooks listed in Modules, one function per name; a name that is not one logs [hamur] Unknown hook "build:dne" (did you mean "build:done"?) |
app.baseURL and app.buildAssetsDir get a leading and a trailing / ("docs" becomes "/docs/"); a baseURL with a scheme, a ? or a # is an error. The config is checked when it loads, and all problems are thrown together as Invalid config (hamur.config.ts): with one line each: booleans (ssr, components, build.minify, server.trustProxy, imports.autoImport, prerender.crawl, prerender.failOnError, prerender.staticPages, prerender.sharedData, devServer.prefetch, devServer.tasks), build.compressPublic (a boolean or an object with only the keys gzip, brotli and zstd, each a boolean), devServer.port (an integer from 0 to 65535, a string is not converted), build.assetsInlineLimit (a non-negative integer), build.importProtection.client.deny and build.importProtection.server.deny (arrays of strings and RegExps), server.maxBodySize, server.maxRequestBodySize and prerender.concurrency (positive integers), build.sourcemap, app.trailingSlash, app.caseSensitive, app.history ("hash" with ssr not false is app.history "hash" needs ssr: false), app.routeDiscovery, app.notFoundMode, build.sri, app.crossOrigin, app.speculationRules (app.speculationRules.prerender must be "conservative", "moderate", "eager", "immediate" or false (got "soon")), build.serverBundles (an object whose keys match /^[a-z][a-z0-9-]*$/, build.serverBundles.Admin must match /^[a-z][a-z0-9-]*$/, and whose values are arrays of route rule patterns), prerender.routes and prerender.ignore, prerender.onMissingId and prerender.onUnseenRoutes ("fail", "warn" or "ignore"), prerender.errorPages (a boolean or an array of integers), routeRules[...].redirect, routeRules[...].basicAuth, and a srcDir that does not exist. A top-level key that is neither a key above nor the configKey of a loaded module logs [hamur] Unknown config key "runtimeconfig" (did you mean "runtimeConfig"?) and the build goes on. A config that still sets build.target or experimental, which were removed, logs one line each and loads. A config file that fails to load is reported as Cannot load hamur.config.ts: with the file, line and column; a config that default-exports a function is an error, use defineConfig.
With build.sourcemap unset, a production build writes no client source maps and the server bundle is "linked"; set "external" or "linked" to publish the client maps.
A file that a stylesheet loads with url() (a font, an image) is a hashed file under app.buildAssetsDir when it is larger than build.assetsInlineLimit bytes (default 4096), so a change to the CSS does not make visitors download it again. A smaller file stays inline in the CSS as a data: URI, and 0 emits every file. A file that a script imports is always a hashed file.
import type { HamurConfig, ResolvedConfig } from "hamur";
export const config = { framework: "vue", ssr: false } satisfies HamurConfig;
export function describe(resolved: ResolvedConfig): string {
return `${resolved.framework} on ${resolved.preset}, output in ${resolved.outputDir}`;
}
WebAppManifest, WebAppManifestIcon, WebAppManifestScreenshot, WebAppManifestShortcut
The types of app.manifest: WebAppManifest has the W3C members name, short_name, description, start_url, id, scope, display, display_override, orientation, theme_color, background_color, lang, dir, categories, icons, screenshots and shortcuts, and the other three types are the shapes of an entry of icons, screenshots and shortcuts. See Configuration.
// hamur.config.ts
import { defineConfig, type WebAppManifest } from "hamur";
const manifest: WebAppManifest = { short_name: "Example", display: "standalone", icons: [{ src: "/icon-192.png", sizes: "192x192", type: "image/png" }] };
export default defineConfig({ app: { manifest } });
ConfigHead, BuildConfig, KeyedComposable, PrerenderConfig, StorageMount
The types of app.head, of build, of one entry of build.keyedComposables, of prerender and of one value of storage, for a helper or a wrapper that builds that part of the config. ConfigHead is HeadInput with titleTemplate as a string only, because the config is serialized to the client.
A call of the adapter's three composables gets, whatever its arguments (the run time drops it when the call gave a key), and a call of an entry you add gets, when it has fewer than argumentLength arguments, { [Symbol.for("hamur.key")]: "$s<8 hex>" } as its last argument, in the server build, the client build and hamur dev; the hex is the start of the SHA-256 of <file relative to rootDir, with />:<line>:<column> of the call. Only a call of a name imported from its source counts (@hamur/adapter-<framework> for the three defaults). A module adds an entry with hamur.options.build.keyedComposables.push({ name, source, argumentLength }) in its setup; an entry with the name and source of a default replaces it. See State and Data.
const keyed: KeyedComposable = { name: "useCart", source: "~/cart", argumentLength: 1 }
const prerender: PrerenderConfig = { routes: ["/about"], crawl: true }
const mount: StorageMount = { driver: "memory" }
ImageMeta
The default export of an image imported with ?meta (see Assets). src is the asset URL a plain import gives; width and height are the displayed size, from the file header.
interface ImageMeta {
src: string
width: number
height: number
format: "png" | "jpeg" | "gif" | "webp" | "avif" | "svg"
animated?: true
}
HamurHooks, TsConfigFile
The build hooks as an interface of name to function. hooks in the config is { [name in keyof HamurHooks]?: HamurHooks[name] }, so a wrong name or a wrong signature is a type error. hamur/kit exports the same type.
| Hook | Function |
|---|---|
config:resolved | (options: ResolvedConfig) => void | Promise<void> |
modules:done | () => void | Promise<void> |
pages:extend | (routes: RouteRecord[]) => void | Promise<void> |
server:extend | (serverRoutes: ServerRouteRecord[]) => void | Promise<void> |
templates:extend | (templates: Template[]) => void | Promise<void> |
components:dirs | (dirs: ComponentsDir[]) => void | Promise<void>; before components are scanned, with app/components first, then the addComponentsDir entries, each { path: string; prefix: string; pathPrefix: boolean; extensions?: string[] }; mutable, and again on each hamur dev rescan |
components:extend | (components: ComponentEntry[]) => void | Promise<void>; after the scan and the addComponent entries, before the list is handed to the adapter, each { name: string; file: string; export?: string }; mutable |
prepare:types | (contexts: { app: TsConfigFile; server: TsConfigFile; shared: TsConfigFile; node: TsConfigFile }) => void | Promise<void>; TsConfigFile is { compilerOptions: Record<string, unknown>; include: string[]; exclude: string[] }, a context tsconfig before it is written, with paths relative to .hamur/ |
build:before | () => void | Promise<void> |
build:client:config, build:server:config | (config: Bun.BuildConfig) => void | Promise<void> |
build:done | (outputs: { client: Bun.BuildOutput; server: Bun.BuildOutput }) => void | Promise<void> |
prerender:routes | (routes: Set<string>) => void | Promise<void> |
prerender:page | (page: PrerenderPage) => void | Promise<void>; assign page.body to change the file written, see PrerenderPage |
prerender:done | (pages: PrerenderedPage[]) => void | Promise<void>; { path, status, file } for each file written, on every build |
dev:ready | (info: { url: string }) => void | Promise<void> |
close | () => void | Promise<void> |
HamurModuleOptions
An empty interface that a module fills in to type its options. HamurConfig gets one optional key for every key of it, so the options go under the module's configKey with type checking. hamur/kit exports the same type. See Modules.
import { defineConfig } from "hamur";
declare module "hamur" {
interface HamurModuleOptions {
sitemap?: { hostname?: string };
}
}
export default defineConfig({ modules: ["./modules/sitemap.ts"], sitemap: { hostname: "https://example.com" } });
HeadInput
The type that useHead takes: title, titleTemplate, templateParams, meta, link, script, style, htmlAttrs and bodyAttrs; a tag may have a key. It is the same HeadInput that hamur/app exports. app.head in the config is typed by ConfigHead, the same shape with titleTemplate as a string only. See Head.
import { defineConfig } from "hamur";
import type { HeadInput } from "hamur";
const head = {
title: "Hamur",
titleTemplate: "%s · Hamur",
meta: [{ name: "description", content: "A full-stack framework for Bun" }],
link: [{ rel: "icon", href: "/favicon.svg" }],
} satisfies HeadInput;
export default defineConfig({ app: { head } });
RouteRule
One value of routeRules. Rules are matched by pattern and the more specific pattern wins. See Deploy and Storage and cache.
| Key | Type |
|---|---|
prerender | boolean |
ssr | boolean |
swr | number | boolean |
cache | { maxAge?, swr?, staleMaxAge?, varies? } | false |
headers | Record<string, string> |
redirect | string | { to: string; status?: number } |
cors | boolean | Record<string, unknown> |
proxy | string |
noindex | boolean |
basicAuth | { username: string; password: string | { runtimeConfig: string }; realm?: string } | false |
appLayout | string | false |
appMiddleware | string | string[] | Record<string, boolean> |
speculation | false |
stream | boolean |
basicAuth asks for HTTP Basic credentials (see requireBasicAuth) for every path under the pattern, public files and prerendered pages included, before static files and routing; false lifts a less specific rule. Take the password from { runtimeConfig: "<key>" }: a literal in the config file warns at build, a key the config does not declare fails it. A CORS preflight passes without credentials when the same rule has cors. The rule covers paths, so a handler call (/_hamur/fn/<id>) is protected by defineMiddleware({ server: basicAuth(…) }) on the handler. A path that is a file stands for the route it serves, so a rule on /admin also guards /admin/index.html, and paths match exactly: /ADMIN is not /admin. On static the build fails; on vercel, netlify and cloudflare a prerendered page under the rule fails the build and a file of the output's public/ (including the /_hamur/ bundles under a /** rule) warns, since the platform serves them before the function.
speculation: false leaves the matching paths out of the speculation rules of app.speculationRules, and a page document it matches gets no rules script; on a page write meta.rules: { speculation: false } (meta.speculation fails the build). Any other value fails the load: routeRules["/x"].speculation must be false (got true).
stream says whether the matching pages send their document while they render (true) or whole (false); without it the adapter's default applies, which streams in every adapter but vue. On a page write meta.rules: { stream: false } (meta.stream fails the build: meta.stream in app/pages/feed.vue is not a page meta key; write meta.rules: { stream: true }). A page is sent whole anyway for a HEAD request, under swr, cache or prerender, in the prerender and hamur generate, when it is script-free and for a user-agent that app.htmlLimitedBots matches; stream: true beside prerender, swr or cache on one pattern logs routeRules["/x"].stream: true has no effect: the path is cached by swr, and a cached answer is buffered at build. A status, header or cookie a component sets after the first chunk is dropped, and hamur dev logs it: useResponseHeader("x-a") set after the response started streaming on /x; ignored. A value that is not a boolean fails the load: routeRules["/x"].stream must be a boolean (got "yes").
appLayout is the layout of the matching pages whose meta.layout sets none, before default. appMiddleware runs named route middleware for the matching paths, after the global ones and before each page's meta.middleware, on the server and on client navigations; { analytics: false } takes a global one out for those paths and never a page's own meta.middleware. Overlapping patterns merge by name, the more specific last, so "/admin/public/**": { appMiddleware: { auth: false } } lifts the auth of "/admin/**": { appMiddleware: ["auth"] }. A name with no file in app/layouts or app/middleware fails the build: routeRules["/admin/**"].appMiddleware names "auth", which is not in app/middleware.
import { defineConfig } from "hamur";
import type { RouteRule } from "hamur";
const docs: RouteRule = { prerender: true, headers: { "x-robots-tag": "all" } };
const legacy: RouteRule = { redirect: { to: "/docs", status: 301 } };
export default defineConfig({ routeRules: { "/docs/**": docs, "/old": legacy } });