Skip to content

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

Configuration

hamur.config.ts in the app root default-exports the config, wrapped in defineConfig so the editor checks the keys. The hamur reference lists every key with its type; this page covers the two that carry your own values, runtimeConfig and appConfig, how environment variables and .env files reach them, and the keys for hosts, link protocols, teleports, prerender conflicts, the Cloudflare environment and the cache deadline.

Runtime config

runtimeConfig holds values that can change per deployment. Keys at the top level are private: they stay on the server. Keys under public are sent to the browser.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  runtimeConfig: {
    apiSecret: "",
    oauth2ClientId: "",
    limits: { perMinute: 60 },
    public: { siteName: "My shop", apiBase: "/api" },
  },
  appConfig: { theme: "light" },
});

Read it on the server with useRuntimeConfig(event) from hamur/server, or without the event (also at module scope, and as server.runtimeConfig in a server plugin). It returns the whole object, private keys and public. A load gets the client part as ctx.runtimeConfig.

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

export const site = defineHandler({
  route: "/api/site",
  method: "GET",
  handler(_, { event }) {
    const config = useRuntimeConfig(event);
    return { signed: typeof config.apiSecret === "string" && config.apiSecret !== "", site: (config.public as { siteName?: string }).siteName };
  },
});

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: public is the public part, and app is { baseURL, buildAssetsDir }. The private keys are never in it.

tsx
import { useAppConfig, useRuntimeConfig } from "@hamur/adapter-react";

export default function Header() {
  const { public: site, app } = useRuntimeConfig();
  const settings = useAppConfig();
  return (
    <header data-theme={String(settings.theme)}>
      <a href={app.baseURL}>{String(site.siteName)}</a>
    </header>
  );
}

process.env is not the way to read a value in client code. hamur build and hamur generate fail when a client module reads process.env.<NAME> other than NODE_ENV, with app/components/banner.tsx:2:13: process.env.SITE_NAME reaches the client bundle; use useRuntimeConfig().public, import.meta.env or #hamur/env/public, and hamur dev shows the same text as a warning. Code under server/ is not checked, and neither is a read behind import.meta.server or a typeof process test. Put the value in runtimeConfig.public and read it with useRuntimeConfig():

tsx
export default function Banner() {
  return <p>{process.env.SITE_NAME}</p>;
}
tsx
import { useRuntimeConfig } from "@hamur/adapter-react";

export default function Banner() {
  return <p>{String(useRuntimeConfig().public.siteName)}</p>;
}

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 of runtimeConfig.public are typed on useRuntimeConfig().public. The object that useRuntimeConfig(event) returns is shared by every request: do not change it.

Environment variables

A variable overrides a key of the config when the server starts:

  • HAMUR_<KEY> overrides the top-level key <KEY>, and HAMUR_PUBLIC_<KEY> overrides the key under public.
  • The key is written in upper snake case: apiBase is API_BASE, oauth2ClientId is OAUTH2_CLIENT_ID, and a capital run ends before the last capital that starts a word: apiURLBase is API_URL_BASE, so HAMUR_API_URL_BASE overrides it and HAMUR_PUBLIC_API_URL_BASE overrides the public one.
  • Only keys the config declares are overridden. A variable for a key that is not in runtimeConfig does nothing, and so does HAMUR_PUBLIC alone.
  • Only top-level keys are matched. To change a key that holds an object, set the whole object as JSON.
  • A value that is valid JSON is parsed (120 is a number, true a boolean, {"perMinute":120} an object); any other value stays a string.
  • The variables are read once, at server start. Changing one needs a restart.
env
HAMUR_API_SECRET=s3cret
HAMUR_OAUTH2_CLIENT_ID=abc123
HAMUR_LIMITS={"perMinute":120}
HAMUR_PUBLIC_SITE_NAME=Corner shop

With this file and the config above, useRuntimeConfig(event).limits is { perMinute: 120 } and useRuntimeConfig().public.siteName is Corner shop.

For values that need a schema, a type and a check at start, declare them in app/env.ts; see Environment. Modes (--mode staging) and the $production and $env config blocks are there too.

.env files

hamur dev, build, generate and preview read .env, .env.<mode> and .env.local from the app root, and --dotenv <file> adds another file; Getting started has the details. A variable already set in the shell wins over the files.

A built server does not read these files. Bun loads a .env from the working directory when it starts a process, and Node loads none, so in production set real environment variables on the host.

App config

appConfig in the config, merged with the default export of app/app.config.ts, is the app config. The file wins on a conflict. useAppConfig() returns it in every library, and defineAppConfig from hamur/app types the file. It is bundled into the browser build and sent with the page, so it is public: never put a secret in it. It is not changed by environment variables.

ts
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" },
});
KeyDefaultMeaning
devServer.allowedHosts[]extra hosts that hamur dev and hamur preview answer. An entry is an exact name, or starts with . for the name and every subdomain (.ngrok.app admits a.ngrok.app); true allows every host. localhost, *.localhost, IP addresses and the --host or devServer.host value are always allowed. Any other host gets a 403 that names it. A built production server answers any host
devServer.prefetchfalsein hamur dev, Link with prefetchOn="visibility" prefetches nothing, and hover and focus prefetch load the page chunks only and run no load, since each load would run on a server that recompiles. true keeps the data prefetch of a build on hover and focus. A built app is not affected
server.allowedHoststruethe 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.linkProtocols["http", "https", "mailto", "tel", "sms"]the schemes that a Link, navigate(), navigateTo(), redirect() or sendRedirect target may carry, written without : and in lower case. A path, ?query or #hash target has no scheme and is not checked. See Routing
app.prefetchPreloadTagsfalsea 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.cookieStoretruethe 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.staleTime0milliseconds the browser keeps the data of a load fresh; meta.staleTime of a page overrides it. See Data
app.data.gcTime300000milliseconds after a page stops showing its data before the browser deletes it; meta.gcTime overrides it
app.data.staleReload"blocking""background" shows stale data at once and runs the load after the navigation
app.data.refreshOnFocusfalsea number of milliseconds: refresh() when the tab becomes visible, at most once in that time
app.data.refreshOnReconnectfalsetrue calls refresh() when the browser goes online
experimental.offlineRetryfalsea navigation, prefetch or useFetch that failed on the network waits for online and tries again
app.rootTag"div"tag of the app root element, a lower-case HTML tag name. Void and raw-text elements (script, img, textarea, body and the like) fail at load: app.rootTag "script" cannot hold an app
app.rootAttrs{}more attributes of the root element, written after id and escaped; id is app.rootId, so rootAttrs.id fails at load. The server document, the SPA shell, prerendered pages and hamur dev all write them
app.teleportId"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"div"tag of that element
app.teleportAttrs{}more attributes of that element, written after id and escaped
app.manifestunsetthe web app manifest: an object of W3C manifest members, served at <baseURL>manifest.webmanifest as application/manifest+json and linked from every document. name, description and start_url default to site.name, site.description and app.baseURL; the static preset writes the file. false serves none. A public/manifest.webmanifest with app.manifest fails the build
app.asyncData.pendingWhenIdlefalsetrue 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.pageTransitionfalsefalse, or { name, mode?, appear?, duration? }: on a client navigation that swaps the page, the entering elements get <name>-enter-from and <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. mode is "default" (enter and leave together), "out-in" (the new page is hidden until the old one has left) or "in-out"; appear: true also enters the first client-rendered page, never a hydrated one; duration is milliseconds, or { enter, leave }, and defaults to the CSS transition or animation time of the element. A page overrides it with meta.pageTransition: false turns it off, true is 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.layoutTransitionfalseas app.pageTransition, for a navigation that changes the layout; meta.layoutTransition overrides it. A layout swap runs this transition, not the page transition
app.viewTransitionfalsetrue, "always", or { enabled?, types? }: every client navigation runs inside document.startViewTransition with types plus "forward" or "back" as the transition types, and document.documentElement.dataset.hamurDirection holding the direction. "always" also runs under prefers-reduced-motion: reduce. meta.viewTransition of a page and viewTransition of navigate or a link override it (false turns it off). Not run on the first load, for a hash-only or shallow navigation or refresh(), or where startViewTransition is missing; there app.pageTransition and app.layoutTransition run, and they never run together with a view transition. See ViewTransitionOption
app.keepalivefalsetrue or { 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 than max pages (default 10, 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 load app.keepalive has no effect in html apps (no component state). meta.keepalive of a page overrides it (false leaves a page out). A max that is not a positive integer fails at load with app.keepalive.max must be a positive integer (got 0). See onPageActivated
app.navigation.pendingMs, app.navigation.pendingMinMs1000, 500milliseconds, 0 or more. useNavigation().pending turns true pendingMs after a client navigation started, which is also when its pending component (*.pending.*) shows; once true, the navigation's commit (the history write and the update of the page) waits until pendingMinMs have passed since it turned true, so a spinner or pending component never flashes. A navigation that ends before pendingMs never sets it and is never held. meta.pendingMs and meta.pendingMinMs of the target page override both, read once its chunks loaded; a meta.pendingMs that has already passed turns pending true at 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"heading"where the keyboard goes after a client navigation, without scrolling: "heading" focuses the #hash target, else the first [autofocus], else the first h1, 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 under data-hamur-keepfocus, and while a text-entry control has the focus. Any other value fails at load with app.navigation.focus must be "heading", "root" or "none" (got "h1"). See Focus after a navigation
app.navigation.scrollKey"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 #hash or the navigation passes scroll: false. Anything else fails at load with app.navigation.scrollKey must be "entry" or "path" (got "url")
app.navigation.repainttruewhether a click on a link waits one animation frame and the task after it before the navigation starts (before page:beforeNavigate and the middleware), so the click's own styles, such as :active and the pending class, paint first. false starts the navigation at once. A hash-only click on the page on screen, navigate() and useRouter() 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.routeAnnouncer{ politeness: "polite" }false, or { politeness? }: the hidden live region #__hamur_announcer that reads the new page (document.title, else the first h1 that entered, else the path) to a screen reader after the scroll and the focus. "polite" gives aria-live="polite" and role="status", "assertive" gives aria-live="assertive" and role="alert", "off" gives aria-live="off" and no role; false creates no region and announces nothing. Not announced on the first load, for another query or hash only, shallow, refreshAll and refresh. Any other politeness fails at load with app.routeAnnouncer.politeness must be "polite", "assertive" or "off" (got "loud"). See Announcing a page
app.speculationRulesfalsefalse, or { prefetch?, prerender? }, each "conservative", "moderate", "eager", "immediate" or false: 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] and a[rel~="external"] of one with a client). A route rule speculation: false, or meta.rules: { speculation: false } on a page, leaves paths out. See Navigation
app.htmlLimitedBotsHTML_LIMITED_BOTSa RegExp or false: a page request whose user-agent matches is rendered whole before it is sent, so head tags set after a Suspense boundary land in <head>, and event.context.htmlLimitedBot is true. The default, HTML_LIMITED_BOTS from hamur/server, lists link-preview and indexing bots that run no script (facebookexternalhit, Twitterbot, Slackbot, bingbot and others), not Googlebot; false streams to every client. Anything else fails at load with app.htmlLimitedBots must be a RegExp or false (got "bot"), and a pattern with the g or y flag with app.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 stream sets streaming per path, see RouteRule
app.streamTimeout10000milliseconds a deferred value (a promise at the top level of what load returns) 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)
app.link{ 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 Link and every defineLink link, set in one place; a prop on the element still wins. activeClass, exactActiveClass, pendingClass and prefetchedClass (none by default) are class names; externalRelAttribute is the rel of a target="_blank" or other-origin link, false for none; prefetch and prefetchOn ("interaction", "visibility", "tap", "render" or an object of those keys) set the prefetch of a link that gives none of prefetch, prefetchOn and noPrefetch; prefetchDelay is 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.
prerender.routesnonepaths to prerender, or async ({ staticPaths }) => string[] with staticPaths every page path without params; with ssr: false a listed path is written as full HTML and every other path keeps the 200.html shell
prerender.conflict"warn"what the prerender does when two routes give one path, for example blog/new.tsx and blog/[slug].tsx with /blog/new in prerender.routes: "warn" logs it and writes the route the router picks, "error" fails the build, "ignore" says nothing
prerender.staticPagesfalsetrue makes a server-preset build (bun, node, vercel, netlify, cloudflare) also write every page without params whose layouts, parents and page have no load and whose rules do not set ssr: false. A page that marks itself with meta.rules: { prerender: true } is written without it; one that fetches per request sets prerender: false. The static preset writes every page anyway
prerender.onMissingId"warn"what the prerender does with a crawled link /page#x whose written target has no element with id="x" or <a name="x">: "warn" logs / links to /about#nope, but /about has no element with id "nope", "fail" throws it whatever prerender.failOnError says, "ignore" says nothing. An empty fragment and #top always pass
prerender.onUnseenRoutes"warn"what the prerender does with page routes marked for prerender (on the static preset every page; elsewhere prerender: true in a rule or meta.rules) that no seed, entry or link reached, for example /blog/:slug without entries: "warn" names them, "fail" throws whatever prerender.failOnError says, "ignore" says nothing
prerender.sharedDatatruewithin one prerender run, a GET handler called with the same input and a useFetch GET whose key Hamur derived from the URL run once, and every page after the first gets its own copy of the value. A useAsyncData key and a useFetch key option 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 (an Error inside it). A GET handler that reads the request URL to answer shares the first page's answer; set false for it
prerender.errorPages[404]the <status>.html files the static preset writes, each the app error page (app/error.<ext>, else the adapter's) rendered for createError({ status }); true is [404] and false writes 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 logs prerender.errorPages is read by the static preset; on the <preset> preset the server renders error pages
cloudflare.envunsetthe wrangler environment whose env.<name> block the cloudflare build copies into .output/wrangler.json
routeRules[...].cache.maxResolveTime30seconds 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

A value of the wrong type fails when the config loads, with a message that names the key, for example app.teleportId must be a non-empty string (got ""). The keys from app.pageTransition to app.speculationRules are explained, with samples, in Navigation.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  routeRules: {
    "/prices": { cache: { maxAge: 60, maxResolveTime: 10 } },
    "/report": { cache: { maxAge: 3600, maxResolveTime: 0 } },
  },
});