Configuration details
Every rule behind the Configuration guide, and the keys that need more than a line. The hamur reference lists all keys with their types.
Runtime config
- Read
runtimeConfigon the server withuseRuntimeConfig(event)fromhamur/server, or without the event (also at module scope, and asserver.runtimeConfigin a server plugin). It returns the whole object, private keys andpublic. - A
loadgets the client part asctx.runtimeConfig. - In app code (a page, a layout, a component, a plugin) call
useRuntimeConfig()from the adapter, with no event. It returns{ public, app }on the server and in the browser:publicis the public part, andappis{ baseURL, buildAssetsDir }. - The private keys are never in it.
- The server writes the public part into the page once, and the browser starts with the same values the server rendered.
- After
hamur typegen, the keys ofruntimeConfig.publicare typed onuseRuntimeConfig().public. - The object that
useRuntimeConfig(event)returns is shared by every request: do not change it.
process.env in client code
process.envis not the way to read a value in client code.hamur buildandhamur generatefail when a client module readsprocess.env.<NAME>other thanNODE_ENV, withapp/components/banner.tsx:2:13: process.env.SITE_NAME reaches the client bundle; use useRuntimeConfig().public, import.meta.env or #hamur/env/public, andhamur devshows the same text as a warning.- Code under
server/is not checked, and neither is a read behindimport.meta.serveror atypeof processtest. Put the value inruntimeConfig.publicand read it withuseRuntimeConfig():
export default function Banner() {
return <p>{process.env.SITE_NAME}</p>
}
import { useRuntimeConfig } from "@hamur/adapter-react"
export default function Banner() {
return <p>{String(useRuntimeConfig().public.siteName)}</p>
}
Environment variables
- A config value reads a variable only through
env("NAME"), exported byhamur, which names an entry ofapp/env.ts. - The value is read when the server starts, validated by the entry's schema, and replaces the reference. Changing it needs a restart, not a build. On Cloudflare it is read when the worker module loads.
- A name
app/env.tsdoes not declare fails when the config loads, with its path:runtimeConfig.apiSecret reads env "API_SECRT", which app/env.ts does not declare. - A key under
publicmay read only a public entry that is not static, since its value goes to the browser:runtimeConfig.public.apiBase reads env "API_KEY", which is private; mark it public: true in app/env.ts or move the key out of public. - A variable named after a key changes nothing:
HAMUR_API_SECRETdoes not touchapiSecret. - The same
env("NAME")is how a storage mount, a token or a module option reads a secret.
API_KEY=s3cret
GA_ID=G-123
With this file and the config above, useRuntimeConfig(event).apiSecret is s3cret and useRuntimeConfig().public.analyticsId is G-123.
.env files
hamur dev,build,generateandpreviewread.env,.env.<mode>and.env.localfrom the app root, and--dotenv <file>adds another file; Environment has the order.- A variable already set in the shell wins over the files.
- A built server does not read these files.
- Bun loads a
.envfrom the working directory when it starts a process, and Node loads none, so in production set real environment variables on the host.
One public config
- Settings that every page reads and that are not secret, a theme or a site title, go under
runtimeConfig.publicand are read withuseRuntimeConfig().public. There is no second app config: anappConfigkey fails when the config loads withappConfig: the app config was removed; move its keys under runtimeConfig.public in hamur.config.ts, and anapp/app.config.ts(or.js,.mjs) of the app or a layer fails the scan with HAMUR_E1245,app/app.config.ts: the app config was removed; move its keys under runtimeConfig.public in hamur.config.ts. - A module adds its defaults with
updateRuntimeConfig({ public: { … } })ofhamur/kit.
A value of the wrong type
It fails when the config loads, with a message that names the key, for example app.teleportId must be a non-empty string (got "").
This config sets many of the keys below:
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
devServer: { allowedHosts: [".ngrok.app", "app.test"] },
server: { trustProxy: true, allowedHosts: ["example.com", ".example.com"] },
app: {
linkProtocols: ["http", "https", "mailto", "tel", "sms", "whatsapp"],
teleportId: "teleports",
teleportTag: "div",
teleportAttrs: { class: "teleports" },
},
prerender: { conflict: "error" },
cloudflare: { env: "staging" },
})
Dev server
devServer.allowedHosts
Default: [].
- Extra hosts that
hamur devandhamur previewanswer. - An entry is an exact name, or starts with
.for the name and every subdomain (.ngrok.appadmitsa.ngrok.app);trueallows every host. localhost,*.localhost, IP addresses and the--hostordevServer.hostvalue are always allowed. Any other host gets a 403 that names it.- A built production server answers any host.
devServer.prefetch
Default: false.
- In
hamur dev,LinkwithprefetchOn="visibility"prefetches nothing, and hover and focus prefetch load the page chunks only and run noload, since eachloadwould run on a server that recompiles. truekeeps the data prefetch of a build on hover and focus.- A built app is not affected.
devServer.hmr
Default: true.
falseturns off Bun's hot module replacement inhamur dev: every change to a file the browser loads (CSS andpublic/files included) reloads the page, and the adapters emit no hot-update code.truehot-updates a page, keeping its state.- Server-only files and server rebuilds are the same either way.
- Must be a boolean:
devServer.hmr must be a boolean (got "off").
devServer.timing
Default: true.
- In
hamur dev, the browser writes aperformance.measurefor each app plugin setup, app hook call, route middleware, loader run, navigation and hydration, namedhamur:plugin:<name>,hamur:hook:<name>,hamur:middleware:<name>,hamur:loader:<route>andhamur:navigation, on aHamurtrack of Chrome's Performance panel; a loader'sctx.fetchsends atraceparentso the devtools Timeline can nest the server spans. falsewrites none.- A build holds none of it.
- Must be a boolean:
devServer.timing must be a boolean (got "yes").
devServer.mcp
Default: true.
- Serves the dev MCP endpoint
POST <baseURL>_hamur/dev/mcpinhamur devfor coding agents (Dev server);falseleaves the path unanswered, and a build never has it. - Must be a boolean:
devServer.mcp must be a boolean (got "yes").
agentRules
Default: true.
falsemakeshamur agents, and the step ofhamur upgradethat runs it, leaveAGENTS.mdas it is (AI and editors).- Must be a boolean:
agentRules must be a boolean (got "no").
devServer.inspect
Default: false.
- Records every step of the transform chain for
GET /_hamur/inspectinhamur dev, and for the devtools Inspect tab: per module and side, the plugin name, the loader it received, the text it returned and its time, with a line diff against the step before. hamur dev --debugturns it on too; a build answers 404.- The route lists only what was recorded and never reads a file from disk.
- Must be a boolean:
devServer.inspect must be a boolean (got 1).
devServer.console
Default: true.
- Which browser
consolecallshamur devprints in the terminal as[browser] warn x (app/pages/index.tsx:12), with the source-mapped first frame outside Hamur andnode_modules:trueforwardslog,info,debug,warnanderror,"warn"warn and error,"error"error only,falsenone. - The records join the log behind
GET /_hamur/logs, and Bun's own forwarding is off, so a call prints once. - The browser still prints as before.
- Uncaught errors keep the overlay and are not forwarded.
- Must be
true,false,"warn"or"error":devServer.console must be true, false, "warn" or "error" (got "all").
devServer.ssrLogs
Default: true.
- The browser console prints the server log records of the document request as one collapsed
[ssr] <n> log lines for <path>group, after the app hookapp:ssrLogsgot them. GET /_hamur/logsis a dev data route, so a page on another device without the dev token prints no group.- Must be a boolean:
devServer.ssrLogs must be a boolean (got "yes").
devServer.logFetches
Default: true.
- Each server-side
$fetchandctx.fetchof a request prints one indented line under that request's log line inhamur dev:↳ GET /api/me 200 4ms (in-process), with, cache hit,, cache missor, cache stalewhen a cached handler, a route-rule cache or aserverCacheanswered it. - A call to another server prints
(network). - An in-process call prints no request line of its own.
- The URL is the path without its query;
{ fullUrl: true }prints the whole URL, the origin and query included. falseprints none.- Must be a boolean or
{ fullUrl: boolean }:devServer.logFetches must be a boolean or { fullUrl: boolean } (got "yes").
devServer.slowWarning
Default: 4000.
- Milliseconds after which a loader, route middleware, app plugin setup or async-data handler that is still running logs once, on the side where it runs:
[hamur] loader of blog-slug is still running after 4 s (/blog/x), andmiddleware <name>,plugin <name>orasync data <key>for the others. - The server logs it as a record, the browser as a
console.warnthatdevServer.consoleforwards to the terminal. falsesets no timer.- Must be a positive number or
false:devServer.slowWarning must be a positive number of milliseconds or false (got -1).
devServer.updateCheck
Default: false.
hamur devaskshttps://registry.npmjs.org/hamur/latestfor the newesthamurat most once per 24 h and prints[hamur] Hamur 1.2.0 is available (you have 1.1.0)when it is newer.- The request has a 2 s timeout, runs after
Local:so the start never waits for it, and a failure prints nothing. - The time of the last check is kept in
<cacheDir>/update-check.json. It never runs whenCIis set orHAMUR_NO_UPDATE_CHECK=1, and a build or preview has none. - Must be a boolean:
devServer.updateCheck must be a boolean (got "yes").
devServer.chromeWorkspace
Default: true.
hamur devlets Chrome DevTools map the project folder as a workspace: a request for/.well-known/appspecific/com.chrome.devtools.jsonfromlocalhost,127.0.0.1or::1answers{ "workspace": { "root", "uuid" } }with the folderhamur devruns in (the app root, or the common directory of the app and a layer outside it) and auuidthat stays the same across restarts.falseanswers 404; a build has no such route.- Must be a boolean.
devServer.indicator
Default: { position: "bottom-left" }.
- The badge
hamur devdraws on every page, in a shadow root: the server state while it rebuilds or failed, and<route name> · <mode>with the route report's mode (request,prerendered,cached swr 60,cached isr 60,cached cache 60,spa,script-free) from the route rules of the route, as a build would treat it (hamur devrenders every request). - With
@hamur/devtoolson the page the text is in its toolbar and the badge is not drawn. falsedraws none.- A build holds none of it.
positionmust be"bottom-left"or"bottom-right":devServer.indicator.position must be "bottom-left" or "bottom-right" (got "top").
devServer.hydrationMismatch
Default: "overlay".
- How
hamur devreports a page whose first render in the browser differs from the server's HTML (aDate.now(), atypeof windowbranch, a browser extension that edits the page). Each report prints[hamur] hydration mismatch in <component> at <path>in the browser console and, with the route, in the terminal, once per component and path, and counts inwindow.__hamur_hydration. "overlay"also opens a panel at the bottom of the page with the server and client markup of that node side by side, the difference marked and the component file as a link to the editor;"console"gives the lines and the counter without the panel;falsereports nothing, and the library's own warnings print as before.- React reports from its recoverable hydration error (shown in this panel, not in the error overlay), Vue from its hydration warnings and the element they name, Svelte and Preact from the DOM after hydrating against the server markup, html from its render string against the server markup.
- Solid reports only a node it cannot find while hydrating (its own
Hydration Mismatcherror): Solid keeps the server's text and attributes, so a text or attribute difference in a Solid app gives no report. - A build holds none of it.
- Must be
"overlay","console"orfalse:devServer.hydrationMismatch must be "overlay", "console" or false (got true).
Address and proxies
server.allowedHosts
Default: true.
The hosts whose x-forwarded-host header getRequestURL trusts when server.trustProxy is on. Entries match as in devServer.allowedHosts. true trusts any host; without trustProxy the key does nothing.
app.origin
Default: unset.
- The public origin, where browsers reach the server: a scheme, a host and an optional port, no path (
https://example.com). HAMUR_ORIGINreplaces it when the server starts.- When set it is the origin of
getRequestURL(event)anduseRequestURL(), the origin the cross-origin form check expects, the originsendRedirectandredirect()compare to tell an external target, and the origin of absolute URLs the prerender writes; neither theHostheader norx-forwarded-hostandx-forwarded-protochange it, even withserver.trustProxy. - The path and query stay the request's. It is not
site.url: that is the canonical URL search engines see, this is where the server is reached, so a preview deploy sets its ownapp.originand keeps the productionsite.url. app.origin must be an origin such as "https://example.com" (got "https://a.test/x"); a badHAMUR_ORIGINstops the start withHAMUR_ORIGIN must be an origin such as "https://example.com" (got "https://a.test/x").
app.cdnURL
Default: "".
An absolute http: or https: URL that serves the client files; HAMUR_APP_CDN_URL replaces it when the server starts. See Build output.
server.fallbackProxy
Default: unset.
- An absolute
http:orhttps:URL; a request that no public file, handler route or concrete page answers is forwarded there, path and query kept, instead of the 404. - See Fall back to another server.
Server
server.etag
Default: false.
trueor"weak"sends a weaketag,"strong"a strong one, on aGETorHEAD200answer whose body is a string, bytes, a blob or a JSON value of at most 1 MiB and that has noetag,set-cookieorno-store. Anything else:server.etag must be a boolean, "weak" or "strong" (got "x").- See Your own validators.
server.compress
Default: true.
trueis{ threshold: 1024, encodings: ["zstd", "br", "gzip"] }; compresses dynamic answers on the bun and node presets by the first ofencodingsthe request accepts ("deflate"is the fourth), for compressible types ofthresholdbytes or more;falseturns it off.- Other presets: the host compresses.
- A bad value:
server.compress must be a boolean or { threshold?, encodings? } (got "br"),server.compress.encodings entry "lz4" is not a coding; use zstd, br, gzip or deflate. - See Compression.
server.earlyHints
Default: false.
truesends a103 Early Hintson the node preset and aLinkheader on every preset for a page's stylesheets (rel=preload; as=style) and module chunks (rel=modulepreload; crossorigin); see Early hints.
server.pubsub
Default: false.
{ driver: "redis", url?, channelPrefix? }carriespublish,peer.publish,revalidateTag,revalidatePath,invalidateRouteCacheand a cache'sexpire()to the other instances of the app through Redis, withBun.redis: the bun preset only, andhamur dev.urldefaults toREDIS_URLat start,channelPrefixto"hamur:". Another preset fails the build withserver.pubsub needs Bun.redis, which the "node" preset cannot run (it runs on: bun); a start withouturlorREDIS_URLfails withserver.pubsub needs url or REDIS_URL.- See WebSockets.
server.syncedState
Default: false.
trueor{ path?, maxKeys?, maxSubscriptions? }adds the synced state socket route at<baseURL>_hamur/synced(orpath), keeping one JSON value per room and key, at mostmaxKeys(default 10000) of them, with at mostmaxSubscriptions(default 1000) per socket; bun, node and cloudflare withcloudflare.websocket: "durable"only.- Load errors:
server.syncedState.path must start with "/",server.syncedState.maxKeys must be a positive integer,server.syncedState.maxSubscriptions must be a positive integer. - See Synced state.
Cache
routeRules[...].cache.maxResolveTime
Default: 30.
Seconds a cache fill may run before the callers waiting for it get a 504; 0 or Infinity waits without a limit. See Storage and cache.
routeRules[...].cache.staleIfError
Default: none.
- Seconds a page or route entry past its stale window is still served when the fill that replaces it throws or times out, and
stale-if-error=<n>in the rule'sCache-Control. - See Serving stale on error.
routeRules[...].cache.maxEntrySize
Default: half a memory mount's maxBytes.
Bytes; a page or route answer larger than this goes to the client and is not stored. See Entry size.
routeRules[...].cache.base
Default: cache:pages for a page, cache:handlers for a server route, each cache when not mounted.
The storage mount of the rule's entries, or a list of mounts, fastest first, read in order and all written. See Tiers and versions.
storage["cache:pages"], storage["cache:handlers"], storage["cache:functions"], storage["cache:tags"]
Default: unset, so cache.
- The mount of one kind of cache entry: pages, server-only components and server islands; server routes a rule caches; cached functions, a
GEThandler'scacheand$fetchserverCache; the tag index. - Any driver; a kind left out uses
cache. - See Where entries live.
routeRules[...].cache.streamFill
Default: false.
true sends a page or route answer to the request that fills its entry chunk by chunk and stores it when the body ends. See Streaming fills.
routeRules[...].cache.tags
Default: none.
Cache tags of every page and server route the rule stores, which revalidateTag reaches; path:, route: and layout: are refused. See revalidateTag.
routeRules[...].cache, routeRules[...].swr
Default: none.
- A profile name is a rule's lifetime:
cache: "hours"iscache: { profile: "hours" },swr: "hours"iscache: { profile: "hours", swr: true }; an unknown name fails the load:routeRules["/x"].cache: unknown profile "hourz". - See
cacheLife.
routeRules[...].cache.profile
Default: none.
A profile name that gives maxAge, staleMaxAge and clientMaxAge; the rule's own fields win over it.
server.cache.profiles
Default: {}.
- Named lifetimes
{ maxAge, staleMaxAge?, clientMaxAge? }added to the built-inseconds,minutes,hours,days,weeksandmax; an entry of a built-in's name replaces it. - A name is
a-z,0-9and-, starting with a letter;maxAgeis a positive number of seconds. clientMaxAgeaddsmax-age=<n>to theCache-Controla rule sends.
server.cache.defaults
Default: {}.
maxAge,swr,staleMaxAge,profile,maxResolveTime,staleIfErrorandmaxEntrySize, merged under every cached function, handler and rule; a function field fails the load:server.cache.defaults.getKey is not an option here; defaults reach the server as JSON.- A rule
swr: truetakesdefaults.maxAgebefore1.
server.cache.statusHeader
Default: true in hamur dev, false in a build.
truesends the cache status (HIT,STALE,MISS,REVALIDATED,BYPASS) of an answer inx-hamur-cache; a string names the header.- The
statusHeaderoption of a cache and the rule keycache.statusHeaderwin; see Cache status.
server.revalidate
Default: false.
{ token?, path? }turns on the endpointPOST <baseURL>_hamur/revalidate(orpathbelow the base) that runsrevalidateTagandrevalidatePathfor a caller withAuthorization: Bearer <token>.tokenis a string orenv("NAME"); without it the token isHAMUR_REVALIDATE_TOKEN.- At least 32 characters, checked at start.
- See On-demand revalidation.
server.cdnPurge
Default: {}.
- Credentials with which
revalidateTagandrevalidatePathpurge the CDN by tag:cloudflare: { zoneId, token },netlify: { siteId?, token? }(elseSITE_IDandNETLIFY_PURGE_API_TOKEN),vercel: { projectId, teamId?, token }. - A
tokenis a string orenv("NAME"); each host is read by its own preset only. - See CDN tags and purge.
Prerender
prerender.format
Default: "directory".
The file a prerendered page is written to: <path>/index.html, <path>.html ("file") or the page's own file ("preserve"). See Build output.
prerender.workers
Default: 1.
Bun workers that prerender pages from one queue; "auto" is the core count minus one. See Build output.
prerender.routes
Default: none.
- Paths to prerender, or
async ({ staticPaths }) => string[]withstaticPathsevery page path without params; withssr: falsea listed path is written as full HTML and every other path keeps the200.htmlshell.
prerender.conflict
Default: "warn".
- What the prerender does when two routes give one path, for example
blog/new.tsxandblog/[slug].tsxwith/blog/newinprerender.routes:"warn"logs it and writes the route the router picks,"error"fails the build,"ignore"says nothing.
prerender.staticPages
Default: false.
truemakes a server-preset build (bun, node, vercel, netlify, cloudflare) also write every page without params whose layouts, parents and page have noloadand whose rules do not setssr: false.- A page that marks itself with
meta.rules: { prerender: true }is written without it; one that fetches per request setsprerender: false. - The static preset writes every page anyway.
prerender.onMissingId
Default: "warn".
- What the prerender does with a crawled link
/page#xwhose written target has no element withid="x"or<a name="x">:"warn"logs/ links to /about#nope, but /about has no element with id "nope","fail"throws it whateverprerender.failOnErrorsays,"ignore"says nothing. - An empty fragment and
#topalways pass.
prerender.onUnseenRoutes
Default: "warn".
- What the prerender does with page routes marked for prerender (on the static preset every page; elsewhere
prerender: truein a rule ormeta.rules) that no seed, entry or link reached, for example/blog/:slugwithoutentries:"warn"names them,"fail"throws whateverprerender.failOnErrorsays,"ignore"says nothing.
prerender.sharedData
Default: true.
- Within one prerender run, a
GEThandler called with the same input and auseFetchGETwhose key Hamur derived from the URL run once, and every page after the first gets its own copy of the value. - A
useAsyncDatakey and auseFetchkeyoption you chose are never shared. - A call is not kept, and so runs for each page, when it fails, calls
taint(), changes the status, a header or a cookie of the response, or returns a value that would not come back as it was (anErrorinside it). - A
GEThandler that reads the request URL to answer shares the first page's answer; setfalsefor it.
prerender.errorPages
Default: [404].
- The
<status>.htmlfiles the static preset writes, each the app error page (app/error.<ext>, else the adapter's) rendered forcreateError({ status });trueis[404]andfalsewrites none. - A status outside 400-599 is left out and logs
prerender.errorPages: 302 is not an error status; it is left out. On a preset that does not prerender every page a set value logsprerender.errorPages is read by the static preset; on the <preset> preset the server renders error pages.
prerender.cache
Default: false.
truekeeps every written page with acacheKeyin.hamur/cache/prerender/and, on the next build, copies it instead of rendering it while its key and the build's server bundle and client manifest are unchanged.hamur build --forceandhamur generate --forcerender every page.- See Incremental prerender.
prerender.cacheKey
Default: none.
({ path, params }) => string | undefined: the key of a prerendered path;undefinedrenders it every time.- An
entriesitem{ params, cacheKey }sets the key of its own path, before this function.
Platforms
cloudflare.websocket
Default: "durable".
- Where the
cloudflarebuild runs WebSockets:"durable"in the generatedHamurWebSocketDurable Object,"worker"in the Worker's isolate. Any other value fails the load:cloudflare.websocket must be "durable" or "worker" (got "pool").
cloudflare.devBindings
Default: true.
- With the
cloudflarepreset andwranglerinstalled in the app,hamur devloads it and gives every event the bindings of your wrangler config asevent.runtime.env, plusevent.runtime.ctxandevent.runtime.caches. - Local only:
remoteBindings: false, so dev never reaches your Cloudflare account, and a binding that exists only remotely is absent. - Without
wrangler, dev logs once[hamur] Cloudflare bindings are not available in dev; install wrangler in the app to use themand goes on. falseskips it. Not a boolean fails the load:cloudflare.devBindings must be a boolean (got "no").
cloudflare.runWorkerFirst
Default: [].
- Extra patterns for
assets.run_worker_firstin.output/wrangler.json, in Cloudflare's syntax (*matches any characters,/included; a!prefix excludes). - The build already lists the paths of
cors,proxy,basicAuthandipRestrictionrules; yours are added after them. trueruns the Worker for every request.- See Cloudflare.
cloudflare.observability
Default: false.
truewritesobservability: { enabled: true }into.output/wrangler.json, which turns on Workers Logs and traces for the Worker, unless your own wrangler config setsobservability: then yours is kept.- With
server.tracingon, the request span also carriescloud.provider: "cloudflare"andcloudflare.ray(thecf-rayheader). Not written forcloudflare-pages. Not a boolean fails the load:cloudflare.observability must be a boolean (got "yes").
cloudflarePages.routes
Default: computed.
{ include?: string[], exclude?: string[] }: replaces theincludeorexcludelist of the_routes.jsonthat thecloudflare-pagesbuild writes.- Together at most 100 rules, each at most 100 characters; an
excludeentry over a path a route rule needs the Worker for fails the build. - See Cloudflare Pages.
bunCompile
Default: { name: "app" }.
{ target?: Bun.Build.CompileTarget, name?: string }: the target and the file name of the executable the bun-compile preset writes to .output/. See Bun executable.
build.bytecode
Default: false.
boolean: with thebun-compilepreset, the executable carries Bun bytecode of the server, which Bun writes for ESM only into a compiled executable. Any other preset fails:build.bytecode needs the bun-compile preset: Bun writes ESM bytecode only into a compiled executable.- See Bun executable.
build.traceInclude
Default: [].
string[]of globs, relative to the project root, of extra files (a.wasm, a data file) thathamur buildcopies into.output/serverunder the same relative path, beside the traced externals. Each must be a relative glob that stays inside the project:build.traceInclude "../x" must be relative to the project root and stay inside it.
awsLambda.streaming
Default: false.
true exports the aws-lambda handler through awslambda.streamifyResponse and streams the body. See AWS Lambda. Not a boolean fails the load: awsLambda.streaming must be a boolean (got "yes").
firebase.appHosting
Default: {}.
Merged into runConfig of .apphosting/bundle.yaml after runCommand (cpu, memoryMiB, concurrency, maxInstances, minInstances, and any other key App Hosting reads). See Firebase App Hosting.
gitlabPages.publicDir
Default: false.
truealso copies thegitlab-pagesoutput topublic/at the app root.- See GitLab Pages.
- The app's own
publicDirmust not be that folder, and apublic/that Hamur did not write is never replaced; both fail the build. Not a boolean fails the load:gitlabPages.publicDir must be a boolean (got "yes").
cloudflare.env
Default: unset.
The wrangler environment whose env.<name> block the cloudflare build copies into .output/wrangler.json.
Build
cssCompilers
Default: unset.
- The options of the
@hamur/cssmodule:sass,less,stylus(each{ additionalData?, loadPaths? }) andpostcss(boolean, or{ config?, plugins? }). - Typed once the module is installed.
- See Styling and the reference.
cacheDir
Default: node_modules/.cache/hamur.
Where Hamur and its modules keep what a later build can reuse, relative to the root.
skewProtection.keep
Default: 0.
- An integer from 0 to 10: each build saves its files below
.output/public/<buildAssetsDir>in<cacheDir>/skew/<build id>/and copies those of the lastkeepearlier builds into its output, so a tab opened before a deploy still loads its lazy chunks. - A name the new build already has is kept as it is, and older saved builds are removed.
- The kept files are in no service worker list or import map.
<cacheDir>must survive between builds (cache it on CI as you cache the build cache); with nothing saved the build logsskewProtection.keep: no earlier build in node_modules/.cache/hamur/skew.0saves nothing, andhamur devkeeps nothing. Anything else fails the load:skewProtection.keep must be an integer from 0 to 10 (got 1.5), and so does akeepabove 0 withapp.buildAssetsDirat the root:skewProtection.keep needs an app.buildAssetsDir below the root, such as "/_hamur/" (got "/").
build.cache
Default: false.
Skip an unchanged client and server build by a stored archive in <cacheDir>/build/. See Build output.
build.minifyHtml
Default: false.
Drops whitespace that cannot show from the document shell and from an html app's body. See Build output.
build.compileHints
Default: false.
//# allFunctionsCalledOnLoad on the entry, layout and page chunks. See Build output.
build.sourcemapIgnoreList
Default: true.
Writes x_google_ignoreList into every source map. See Build output.
build.extractAsyncDataHandlers
Default: false.
Static preset only: moves a handler that provably uses nothing of its component into its own chunk. See Build output.
publicAssets
Default: [].
- More public directories,
Array<{ dir, baseURL?, maxAge? }>. Each entry is anaddPublicAssetscall made for the app:diris fromrootDir,baseURLstarts and ends with/(default"/"), andmaxAgeseconds give its filescache-control: public, max-age=<n>, immutable;publicDirkeepsmax-age=0, must-revalidate. - The files are served in dev and copied to
.output/public/. - Two sources of one path fail the build naming both. Not an array of that shape fails the load:
publicAssets must be an array of { dir, baseURL?, maxAge? }.
Experiments and future defaults
experimental.offlineRetry
Default: false.
A navigation, prefetch or useFetch that failed on the network waits for online and tries again.
experimental.islands
Default: false.
true, or{ libraries? }in an html app: turns on island pages (meta.hydrate: "islands"), server islands (app/server-islands/) andprerender: "shell".- See Islands and streaming.
librariesis a list of"react","preact","vue","svelte"or"solid"and fails at load outside the html adapter:experimental.islands.libraries is only for html apps.
experimental.svelteAsync
Default: false.
Lets a Svelte component use await in its script or markup, on the server and in the browser; needs the svelte adapter. See Islands and streaming.
experimental.reactCompiler
Default: false.
- Runs Bun's React Compiler over the app's
.jsxand.tsxfiles inhamur build(memoized client code, unmemoized server output);hamur devruns the source as written. - Needs the react adapter:
experimental.reactCompiler needs the react adapter (framework is "vue").
future
Default: {}.
- One boolean per future flag: a default the next major changes, opted into before that major. Each flag is documented with the major that makes it the default, and is removed in that major.
- No flag exists yet, so a key under
futurelogs[hamur] Unknown future key "x"; known keys: none, andfuture: {}is valid. hamur infolists the flags that are on.- To add a flag, a change names the major in the
HamurFutureFlagsentry and gives the flag a reader.
experimental.mcp
Default: false.
true lets the mcp key of defineHandler serve an MCP endpoint; off, a handler with the key fails the build with server/mcp.ts#mcp: the mcp key needs experimental.mcp: true. See MCP.
experimental.runtimeBaseURL
Default: false.
true lets HAMUR_APP_BASE_URL replace app.baseURL when the server starts; the bun and node presets only. See Build output.
The page document
appId
Default: "hamur".
- The prefix of every browser-side name Hamur owns, so several Hamur apps run on one page: lower-case letters, digits and
-, starting with a letter (appId must be lower-case letters, digits and "-", starting with a letter (got "My App")). - With
appId: "shop"the payload script is__shop_payload, the defaultapp.rootIdis__shop, thewindowglobals are__shop_…, thesessionStoragekeysshop:…(shop:reload), the history key fieldsshopKeyandshopIndex, the import map's chunk specifiers#shop-chunk/<key>, the island element<shop-island>and the SPA loader__shop_loader. - The default keeps today's names.
- The DOM events
hamur:beforenavigate,hamur:navigateandhamur:afternavigatekeep their names and carrydetail.appId. - With any
appIdbut"hamur", the navigator takes link clicks and form submits inside its own root only, leaveshistory.scrollRestorationto the browser and ignores a back or forward to an entry another app wrote. Give each app on the page its ownappIdandapp.baseURL.
react
Default: { strictMode: true }.
{ strictMode?, identifierPrefix? }, react adapter only.strictModewraps the app root inStrictModeinhamur dev, so an effect runs twice on mount, and does nothing in a build.identifierPrefixis theuseId()prefix of the server render and of the app root (islands keep their own).react.strictMode must be a boolean (got "yes"),react.identifierPrefix must be a string (got 1),react needs the react adapter (framework is "vue"). For the errors React reports, hookapp:error.
app.spaLoadingTemplate
Default: app/spa-loading-template.html when it exists.
- The HTML a shell document shows until the client has mounted: a path from the root, or
falseto ignore the file. app.spaLoadingTemplate file not found: app/loader.htmlfor a missing one.
app.spaLoader
Default: { tag: "div", attrs: {}, location: "body" }.
The element around the template, id="__hamur_loader" set by Hamur; location is "body" or "within". See Build output.
app.rootTag
Default: "div".
- Tag of the app root element, a lower-case HTML tag name.
- Void and raw-text elements (
script,img,textarea,bodyand the like) fail at load:app.rootTag "script" cannot hold an app.
app.rootAttrs
Default: {}.
- More attributes of the root element, written after
idand escaped;idisapp.rootId, sorootAttrs.idfails at load. - The server document, the SPA shell, prerendered pages and
hamur devall write them.
app.importMap
Default: {}.
- Specifier to URL for modules hosted elsewhere, merged into every document's import map (
hamur devwrites only these);import("remote/widget")stays external in every build and is never hashed, sobuild.sriwrites nointegrityfor it. - A key starting with
#hamur-or a value that is not an absolutehttps:URL or a path starting with/fails at load. There is no shared-library or federation mode.
app.teleportId
Default: "teleports".
id of the element that the document writes after the app root for teleports rendered on the server (Vue <Teleport to="#teleports">, Solid Portal).
app.teleportTag
Default: "div".
Tag of that element.
app.teleportAttrs
Default: {}.
More attributes of that element, written after id and escaped.
app.manifest
Default: unset.
- The web app manifest: an object of W3C manifest members, served at
<baseURL>manifest.webmanifestasapplication/manifest+jsonand linked from every document. name,descriptionandstart_urldefault tosite.name,site.descriptionandapp.baseURL; the static preset writes the file.falseserves none.- A
public/manifest.webmanifestwithapp.manifestfails the build.
app.speculationRules
Default: false.
false, or{ prefetch?, prerender? }, each"conservative","moderate","eager","immediate"orfalse: writes one<script type="speculationrules">in every page document for the links the browser loads as documents (every same-origin link of a document with no client;a[data-hamur-reload]anda[rel~="external"]of one with a client).- A route rule
speculation: false, ormeta.rules: { speculation: false }on a page, leaves paths out. - See Navigation.
app.htmlLimitedBots
Default: HTML_LIMITED_BOTS.
- A
RegExporfalse: a page request whoseuser-agentmatches is rendered whole before it is sent, so head tags set after aSuspenseboundary land in<head>, andevent.context.htmlLimitedBotistrue. - The default,
HTML_LIMITED_BOTSfromhamur/server, lists link-preview and indexing bots that run no script (facebookexternalhit,Twitterbot,Slackbot,bingbotand others), notGooglebot;falsestreams to every client. Anything else fails at load withapp.htmlLimitedBots must be a RegExp or false (got "bot"), and a pattern with thegoryflag withapp.htmlLimitedBots must not use the g or y flag, which makes each test start where the last one ended (got /bot/g). - A route rule
streamsets streaming per path, seeRouteRule.
app.streamTimeout
Default: 10000.
- Milliseconds a deferred value (a promise at the top level of what
loadreturns) may stay pending. - After that it is rejected with a 504
Deferred value timed out, and the streamed document ends once nothing else is pending; a page sent whole waits for its deferred values no longer than this. - Anything but a positive integer fails at load with
app.streamTimeout must be a positive integer of milliseconds (got 0).
Links, navigation and data in the browser
app.linkProtocols
Default: ["http", "https", "mailto", "tel", "sms"].
- The schemes that a
Link,navigate(),navigateTo(),redirect()orsendRedirecttarget may carry, written without:and in lower case. - A path,
?queryor#hashtarget has no scheme and is not checked. - See Routing.
app.prefetchPreloadTags
Default: false.
A prefetch that ran the target page's loads also runs their head exports and adds each link rel="preload" to the document as rel="prefetch"; the next navigation removes them.
app.cookieStore
Default: true.
The browser jar follows the cookieStore change event where the browser has it, so a cookie another tab wrote reaches useCookie without a call to refreshCookie.
app.data.staleTime
Default: 0.
Milliseconds the browser keeps the data of a load fresh; meta.staleTime of a page overrides it. See Data.
app.data.gcTime
Default: 300000.
Milliseconds after a page stops showing its data before the browser deletes it; meta.gcTime overrides it.
app.data.staleReload
Default: "blocking".
"background" shows stale data at once and runs the load after the navigation.
app.data.refreshOnFocus
Default: false.
A number of milliseconds: refresh() when the tab becomes visible, at most once in that time.
app.data.refreshOnReconnect
Default: false.
true calls refresh() when the browser goes online.
app.asyncData.pendingWhenIdle
Default: false.
true makes pending of useAsyncData and useFetch also true for an idle entry that has no data yet, for example one started with immediate: false.
app.pageTransition
Default: false.
false, or{ name, mode?, appear?, duration? }: on a client navigation that swaps the page, the entering elements get<name>-enter-fromand<name>-enter-active, then<name>-enter-to, and a clone of each leaving element stays in place with the<name>-leave-*classes until the leave ends.modeis"default"(enter and leave together),"out-in"(the new page ishiddenuntil the old one has left) or"in-out";appear: truealso enters the first client-rendered page, never a hydrated one;durationis milliseconds, or{ enter, leave }, and defaults to the CSS transition or animation time of the element.- A page overrides it with
meta.pageTransition:falseturns it off,trueis this value, an object merges over it key by key. - Skipped under
prefers-reduced-motion: reduce, for a hash-only or shallow navigation,refresh()and the error page. - See
PageTransition.
app.layoutTransition
Default: false.
As app.pageTransition, for a navigation that changes the layout; meta.layoutTransition overrides it. A layout swap runs this transition, not the page transition.
app.viewTransition
Default: false.
true,"always", or{ enabled?, types? }: every client navigation runs insidedocument.startViewTransitionwithtypesplus"forward"or"back"as the transition types, anddocument.documentElement.dataset.hamurDirectionholding the direction."always"also runs underprefers-reduced-motion: reduce.meta.viewTransitionof a page andviewTransitionofnavigateor a link override it (falseturns it off). Not run on the first load, for a hash-only or shallow navigation orrefresh(), or wherestartViewTransitionis missing; thereapp.pageTransitionandapp.layoutTransitionrun, and they never run together with a view transition.- See
ViewTransitionOption.
app.keepalive
Default: false.
trueor{ max? }: a page keeps its component instances when a client navigation leaves it and is shown again with its state, until the entry above it leaves, the layout changes or more thanmaxpages (default10, counted over the whole app, least recently shown dropped first) are kept.- React keeps a page in
<Activity mode="hidden">, Vue in<KeepAlive>, Preact, Solid and Svelte in<div hidden data-hamur-keepalive>; an html app keeps nothing and warns at loadapp.keepalive has no effect in html apps (no component state). meta.keepaliveof a page overrides it (falseleaves a page out).- A
maxthat is not a positive integer fails at load withapp.keepalive.max must be a positive integer (got 0). - See
onPageActivated.
app.navigation.pendingMs, app.navigation.pendingMinMs
Default: 1000, 500.
- Milliseconds,
0or more. useNavigation().pendingturnstruependingMsafter a client navigation started, which is also when its pending component (*.pending.*) shows; oncetrue, the navigation's commit (the history write and the update of the page) waits untilpendingMinMshave passed since it turnedtrue, so a spinner or pending component never flashes.- A navigation that ends before
pendingMsnever sets it and is never held. meta.pendingMsandmeta.pendingMinMsof the target page override both, read once its chunks loaded; ameta.pendingMsthat has already passed turnspendingtrueat once.- A value that is not a finite number of 0 or more fails at load with
app.navigation.pendingMs must be a finite number of milliseconds, 0 or more (got -1).
app.navigation.focus
Default: "heading".
- Where the keyboard goes after a client navigation, without scrolling:
"heading"focuses the#hashtarget, else the first[autofocus], else the firsth1, else the app root, among the elements the navigation put on screen;"root"focuses the app root;"none"moves nothing. - An element that is not focusable gets
tabindex="-1"until it blurs. - Skipped for a navigation that keeps the page with another query or hash only,
shallow,refreshAll,keepFocus: true,scroll: false, a link underdata-hamur-keepfocus, and while a text-entry control has the focus. Any other value fails at load withapp.navigation.focus must be "heading", "root" or "none" (got "h1"). - See Focus after a navigation.
app.navigation.scrollKey
Default: "entry".
- How a saved scroll position is keyed:
"entry"per history entry, so only back, forward and a reload restore it;"path"per pathname, so a push to a page you scrolled before restores that position too, unless the target has a#hashor the navigation passesscroll: false. - Anything else fails at load with
app.navigation.scrollKey must be "entry" or "path" (got "url").
app.navigation.repaint
Default: true.
- Whether a click on a link waits one animation frame and the task after it before the navigation starts (before
page:beforeNavigateand the middleware), so the click's own styles, such as:activeand the pending class, paint first. falsestarts the navigation at once.- A hash-only click on the page on screen,
navigate()anduseRouter()calls from code never wait. - A value that is not a boolean fails at load with
app.navigation.repaint must be a boolean (got "yes").
app.update.pollInterval, app.update.reloadOnNavigate
Default: 3600000, true.
- How a production client finds a newer deployment.
pollIntervalis a positive integer of milliseconds, orfalse: the client fetches<baseURL>_version.jsonthat often while the tab is visible, and when the tab becomes visible again after 60 s or more;falseturns both off, but an answer of_hamur/fn/,_hamur/islands/or_hamur/components/that carries anotherx-hamur-buildstill starts one check.reloadOnNavigate: truemakes the next navigation after an update is known (aLink,navigate(), back or forward) a full load of its target;falseleaves it a client navigation.hamur devnever checks.useAppUpdateand theapp:updatehook report the update.
app.restoreState
Default: false.
- The default of
persistStateinreloadApp, so a reload Hamur starts (a chunk error, an app update,usePwa().update()) carries the app state over insessionStorage: auseStatevalue, aDateor aMapis back after the page has mounted. - Values reach plain
sessionStorage, which is why it is off by default. - Reading the item back needs no key; see
reloadAppin the app reference.
app.chunkErrors
Default: "reload".
- What Hamur does when a chunk fails to load after a deploy:
"reload","reload-immediate"or"manual". - A page, layout or app-root chunk is tried twice; with
"reload"and"reload-immediate"the second failure reloads the URL once per 10 s (the reload stamp), with"manual"it reloads nothing, callsapp:chunkErrorwithreload: falseand shows the 503 error page, or the page as it is. - An
import()of your own code (a lazy component) that fails is thrown to its caller in every mode and reported toapp:chunkErrorwithstage: "lazy";"reload"also checks for an app update, so the next navigation is a full load,"reload-immediate"also reloads the current URL once per 10 s,"manual"does neither. - Any other value fails at load with
app.chunkErrors must be "reload", "reload-immediate" or "manual" (got "auto").
app.routeAnnouncer
Default: { politeness: "polite" }.
false, or{ politeness? }: the hidden live region#__hamur_announcerthat reads the new page (document.title, else the firsth1that entered, else the path) to a screen reader after the scroll and the focus."polite"givesaria-live="polite"androle="status","assertive"givesaria-live="assertive"androle="alert","off"givesaria-live="off"and no role;falsecreates no region and announces nothing. Not announced on the first load, for another query or hash only,shallow,refreshAllandrefresh. Any other politeness fails at load withapp.routeAnnouncer.politeness must be "polite", "assertive" or "off" (got "loud").- See Announcing a page.
app.link
Default: { activeClass: "router-link-active", exactActiveClass: "router-link-exact-active", pendingClass: "router-link-pending", externalRelAttribute: "noopener noreferrer", prefetch: true, prefetchOn: "interaction", prefetchDelay: 0 }.
- The defaults of every
Linkand everydefineLinklink, set in one place; a prop on the element still wins. activeClass,exactActiveClass,pendingClassandprefetchedClass(none by default) are class names;externalRelAttributeis therelof atarget="_blank"or other-origin link,falsefor none;prefetchandprefetchOn("interaction","visibility","tap","render"or an object of those keys) set the prefetch of a link that gives neitherprefetchnorprefetchOn;prefetchDelayis the milliseconds a hover or focus waits before it prefetches, for a link without the prop.- A key of a wrong type fails the config load, for example
app.link.prefetchOn must be "interaction", "visibility", "tap", "render" or an object of those keys (got "hover"). It is sent to the browser with the app config.
A cache deadline for one kind of entry
import { defineConfig } from "hamur"
export default defineConfig({
framework: "react",
routeRules: {
"/prices": { cache: { maxAge: 60, maxResolveTime: 10 } },
"/report": { cache: { maxAge: 3600, maxResolveTime: 0 } },
},
})