Navigation
Routing shows how a link turns into a client navigation. This page covers what the user sees and feels while it runs: transitions between pages, View Transitions, the keep-alive of a page, the loading indicator and the pending state, the announcement and focus that make a navigation usable without a mouse, scroll, every Link option, the prefetch triggers and what each costs, Speculation Rules, and the events a script outside the app can listen to.
The component samples use React. The other libraries use the same names; Adapters lists what differs, and the table in each section below says where an adapter does something of its own.
The order of one navigation
The core runs every rule on this page, in this order; an adapter only renders. A step in bold is described below.
- A click on a link first repaints: the navigator waits one animation frame and the task after it, so the click's own styles (
:active, the pending class) are on screen before the work starts.app.navigation.repaint: falseskips the wait. A call tonavigate()from code, a hash-only click on the page on screen and a back or forward never wait. page:beforeNavigate,onBeforeNavigate, the clickedLink'sonBeforeNavigate, thehamur:beforenavigateevent, the blockers, the leave and update guards, the route middleware,beforeEach,page:start.- The page chunks and the data load.
pendingturns true afterpendingMsand the pending component paints. onNavigate, thehamur:navigateevent, then the commit waits untilpendingMinMshave passed sincependingturned true.- The history entry is written. Then, in one of two ways, the page changes: inside a view transition (
document.startViewTransition), where the update, the head, the stylesheets and the scroll are its callback, or, without one, through the page or layout transition, or a plain swap. page:finish, the scroll, the focus, the announcement,idle(pendingis false again),page:rendered,onAfterNavigate, thehamur:afternavigateevent,afterEach, the route hooks,onPageActivatedandonPageDeactivated, andpage:transition:finishonce the enter ended.
Where a key is read matters. A key under app in hamur.config.ts is known at build time and reaches the browser through the config. A key in a page's meta is read in the browser once the page's chunk loaded, and after the route middleware, which may set it on to.meta. The exceptions are routeRules[...].speculation and meta.rules.speculation: the build writes the speculation rules, so they are read there.
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
app: {
pageTransition: { name: "fade", mode: "out-in" },
layoutTransition: { name: "slide", duration: { enter: 250, leave: 150 } },
viewTransition: { types: ["slide"] },
keepalive: { max: 5 },
navigation: { pendingMs: 400, pendingMinMs: 300, focus: "heading", scrollKey: "path", repaint: true },
routeAnnouncer: { politeness: "polite" },
link: { prefetchOn: "interaction", prefetchDelay: 100, pendingClass: "is-pending", prefetchedClass: "is-ready" },
speculationRules: { prefetch: "moderate", prerender: false },
},
routeRules: {
"/r/**": { speculation: false },
},
});
Page and layout transitions
app.pageTransition and app.layoutTransition are false (the default) or { name, mode?, appear?, duration? }. A page's meta.pageTransition and meta.layoutTransition override them: false turns the transition off for a navigation to that page, true is the app's value, and an object is merged over the app's key by key, so { name: "slide" } keeps the app's mode. The target page's meta decides both the leave and the enter. A route middleware may set to.meta.pageTransition, for example a name that follows the direction of the move.
nameis the class prefix:<name>-enter-from,<name>-enter-active,<name>-enter-to, and the same three withleave.modeis"default"(leave and enter together),"out-in"(the new page ishiddenuntil the old one has left and the page scrolled) or"in-out"(the old page leaves after the new one entered).appear: truealso enters the first client-rendered page, never a hydrated one: its HTML is already painted, and an-enter-fromclass would hide it again.durationis milliseconds, or{ enter, leave }. Without it, a transition ends at the firsttransitionendoranimationendof its element, or after the longest computed CSS duration plus delay.
.page-enter-active,
.page-leave-active {
transition: opacity 200ms ease, transform 200ms ease;
}
.page-enter-from,
.page-leave-to {
opacity: 0;
transform: translateY(8px);
}
A navigation that swaps the page runs the page transition, one that changes the layout (or the app root) runs the layout transition, and a layout swap with no layoutTransition runs none even when pageTransition resolves. The same route with other params is a page swap; the same page with another query or hash is neither, so a list that re-renders its rows is never taken for a page.
import type { PageMeta } from "hamur/app";
export const meta = {
pageTransition: { name: "slide", mode: "out-in" },
layoutTransition: false,
} satisfies PageMeta;
export default function Report() {
return (
<article>
<h1>Report</h1>
<nav data-hamur-transition="none">Breadcrumb</nav>
</article>
);
}
How it runs, in the same way in every adapter:
- The core finds the entering elements (the elements the update added or showed) and the leaving elements (the ones it removed or hid), outermost only; text nodes count for neither. It puts a ghost where each leaving element was: a clone with every
idremoved,inert,aria-hidden="true"anddata-hamur-ghost. The ghost acts on nothing (it has nonameorformon its controls, nosrcof aniframe, no autoplay, noautofocus, and noscript,object,embed,linkorsourceinside it). The leave classes go on the ghost, never on the library's own node, which the library may still hold. A leaving element that is, or holds, a custom element gets no ghost: it leaves without an animation and the entering elements still enter. data-hamur-transition="none"on an element, or inside one, leaves it out. A layout that mounts a new element on the same update, a breadcrumb keyed by the route for example, would count as entering; mark it.- A newer navigation aborts the older one's transition: its classes and ghosts go,
hiddenleaves its entering elements, and the new navigation treats them as leaving.hiddenthat your own markup set stays. - A swap with a resolved transition that added and removed no element runs none, and logs once per route in
hamur dev:pageTransition on /about needs an element: the update added or removed none. A page that React, Preact, Vue, Svelte or Solid keeps mounted patches its elements in place (the same page component with the samemeta.key), so going from one/blog/:slugto another is such a swap; givemeta.keya value that changes with the param when the page must animate between params. page:transition:finish(route)is an app hook (browser only) that runs once, after the last enter. No transition runs for the first load, a hash-only or shallow navigation,refresh(), an intercepted route, the error page, or underprefers-reduced-motion: reduce.
| react, vue, preact, svelte, solid | html | |
|---|---|---|
| entering and leaving elements | the core observes the root's DOM changes around update | the adapter's client entry returns them from transitionTargets, from the comments <!--hamur-page--> and <!--hamur-layout--> that its server and client renders write around the page and layout |
| why | no library lets the core ask a component for its DOM nodes, and one rule in the core is one behaviour for six adapters | its update replaces the whole root, so the DOM changes name the layout too |
A load that fails the config check says so: app.pageTransition must be false or { name, mode?, appear?, duration? } (got "fade"), and the same for mode and duration. A page meta value of the wrong type logs once in dev and the navigation swaps.
View transitions
app.viewTransition is false, true, "always" or { enabled?, types? }. A navigation runs inside document.startViewTransition when, in this order, the viewTransition option of navigate or Link, else meta.viewTransition, else app.viewTransition turns it on and the browser has startViewTransition. { types: ["slide"] } turns it on (enabled left out means on); false turns it off at any level. The page's types are added to the app's, unless its meta.viewTransition is false. Where the browser has no View Transitions, the page or layout transition runs instead, so write both when a browser without them matters. The two never run together.
prefers-reduced-motion: reduce turns a view transition off, unless the value is "always". Neither runs for the first load, a hash-only or shallow navigation or refresh(); a same-page navigation with another query does.
The transition's types are the configured ones, the page's, the link's, and "forward" or "back" (a back to a lower history index). document.documentElement.dataset.hamurDirection holds the same word before the transition starts, for CSS. Browsers with ViewTransition.prototype.types get { update, types }; the others get the callback alone.
import { Link, transitionName, useRouter } from "@hamur/adapter-react";
import type { PageMeta } from "hamur/app";
export const meta = { viewTransition: { types: ["card"] } } satisfies PageMeta;
export default function Shop() {
const router = useRouter();
return (
<ul>
<li>
<img src="/lamp.jpg" alt="Lamp" {...transitionName("product-lamp")} />
<Link to="/shop/lamp" viewTransition>Lamp</Link>
<Link to="/shop/lamp/specs" viewTransition={{ types: ["slide"] }}>Specs</Link>
<Link to="/cart" viewTransition={false}>Cart</Link>
<button type="button" onClick={() => router.navigate("/shop/lamp", { viewTransition: { types: ["card"] } })}>Open</button>
</li>
</ul>
);
}
An element you want morphed between two pages carries a view-transition-name. transitionName(name) returns what each library spreads on an element: a style object in React, Preact and Vue (v-bind), { style: { "view-transition-name": name } } in Solid, and the string view-transition-name: <name> in Svelte and html. A name that is not a CSS <custom-ident> throws TypeError('transitionName("1x") is not a CSS identifier'), and so do none, auto, default, match-element and the CSS-wide keywords. A name is unique per page; two elements with one name make the browser skip the transition.
:root:active-view-transition-type(card)::view-transition-group(product-lamp) {
animation-duration: 300ms;
}
html[data-hamur-direction="back"]::view-transition-old(product-lamp) {
animation-duration: 150ms;
}
import "hamur/transitions.css" once (in the app root, a layout or your global CSS) gives two presets inside @media (prefers-reduced-motion: no-preference). As view transitions, fade is the default animation of root and slide applies when the transition's types hold slide, reversed under html[data-hamur-direction="back"]. As page transitions, pageTransition: { name: "fade" } or "slide" works with the file alone (.fade-enter-active, .fade-leave-active, .fade-enter-from, .fade-leave-to and the .slide-… set). A browser without :active-view-transition-type() drops the slide rules and fades. hamur/transitions.css lists the details.
What to know about the callback: the browser holds the page's paint until it finishes, so a scrollBehavior that returns a promise must not wait for a frame or for page:transition:finish inside a view transition; it would wait for the browser's timeout. The app hook page:view-transition:start(transition) runs once per transition with ready, finished, updateCallbackDone and skipTransition(). A newer navigation skips the running transition. React's own <ViewTransition> does nothing during a Hamur navigation: React is not asked to start one, so use transitionName().
Keep-alive
A page normally loses its component state when a navigation leaves it. With app.keepalive: true (or { max }, default 10), every page keeps its component instances and its state, hidden, and shows them again when you come back; meta.keepalive overrides it per page (false leaves a page out). A kept page is dropped when the entry above it leaves the screen, the layout changes, or more than max pages are kept (the least recently shown goes first). max is only in the config: all kept pages of an app share one cache. A page that is shown again still runs its load as the client data cache decides.
| react | vue | preact, svelte, solid | html | |
|---|---|---|---|---|
| a kept page is | <Activity mode="hidden">, which unmounts its effects | <KeepAlive> | inside <div data-hamur-keepalive="<key>" style="display:contents">, hidden while kept; its effects keep running | not kept |
In Preact, Svelte and Solid the wrapper div is in the DOM from the server render on, so a selector such as main > article does not match a kept page. An html app has no component state to keep: app.keepalive set in one warns at load with app.keepalive has no effect in html apps (no component state), and a meta.keepalive: true it reads in the browser logs once per route in dev meta.keepalive of /x has no effect in html apps (no component state) (the build cannot read a run-time key). html also has no onPageActivated: its page script already runs on every mount.
onPageActivated(fn) and onPageDeactivated(fn) run when the page is shown and hidden (and on mount and unmount). Start and stop timers and subscriptions in them: in Preact, Svelte and Solid a hidden page keeps running its effects. Focus inside a hidden page is lost, and the focus step moves it.
import { onPageActivated, onPageDeactivated } from "@hamur/adapter-react";
import { useRef, useState } from "react";
import type { PageMeta } from "hamur/app";
export const meta = { keepalive: true } satisfies PageMeta;
export default function Inbox() {
const [query, setQuery] = useState("");
const timer = useRef<ReturnType<typeof setInterval>>(undefined);
onPageActivated(() => {
timer.current = setInterval(() => console.log("poll"), 5000);
});
onPageDeactivated(() => clearInterval(timer.current));
return <input value={query} onChange={(event) => setQuery(event.target.value)} />;
}
The loading indicator
<LoadingIndicator /> is a thin bar fixed at the top of the page. It starts when a navigation (or a form submission) leaves idle, shows only after throttle ms, so a fast navigation shows nothing, estimates its progress, jumps to 100 when the navigation ends, whatever ended it, holds there for hideDelay ms, and resets resetDelay ms later. refresh() and fetchers do not show it. Its props are color ("#2563eb"), errorColor ("#dc2626"), height (3), duration (2000), throttle (200) and estimatedProgress.
It is one <div data-hamur-loading-indicator aria-hidden="true"> with inline styles written by the browser, not by the server render, so a strict style-src is enough. It carries view-transition-name: hamur-loading-indicator, so a view transition does not freeze it in the root snapshot. useLoadingIndicator(options?) returns { progress, isLoading, error, start(), finish({ force?, error? }), set(n), clear() } to draw your own; the state is one per app, and the first LoadingIndicator or useLoadingIndicator call sets its options. See LoadingIndicator.
import type { ReactNode } from "react";
import { Announcer, LoadingIndicator, RouteAnnouncer } from "@hamur/adapter-react";
export default function App({ children }: { children?: ReactNode }) {
return (
<>
<LoadingIndicator color="#0a7" height={2} />
<RouteAnnouncer />
<Announcer />
<main>{children}</main>
</>
);
}
Pending thresholds and the link state
useNavigation() returns { state, pending, to, … }. state is "idle" or "loading"; pending is the switch for slow navigations. It turns true app.navigation.pendingMs (default 1000) after the navigation started, which is also when the route's pending component (*.pending.*, Routing) shows. Once true, the commit waits until pendingMinMs (default 500) have passed since it turned true, so a spinner or pending page is never a flash. A navigation that ends before pendingMs never sets it and is never held. meta.pendingMs and meta.pendingMinMs of the target override both. The clock starts after the leave guards and blockers let the navigation go on; a dialog that waits for a click does not count. A navigation that replaces a pending one starts with pending true and keeps the hold, so a redirect chain does not flash.
The link that started it is marked at once, with no threshold: while a navigation to an anchor's href (path and query, the hash left out) is in flight, the navigator sets aria-busy="true" on it and adds its pending class, router-link-pending unless Link pendingClass or app.link.pendingClass says otherwise ("" adds none); a redirect moves the mark to the anchors of the new target. It marks Links and hand-written anchors that carry data-hamur-prefetch or data-hamur-pending-class. useLinkStatus() inside a Link's children returns { pending } by the same rule; outside a Link it is { pending: false }, and html has the attribute only.
import type { ReactNode } from "react";
import { Link, useLinkStatus, useLoadingIndicator, useNavigation } from "@hamur/adapter-react";
import type { PageMeta } from "hamur/app";
export const meta = { pendingMs: 150, pendingMinMs: 400 } satisfies PageMeta;
function Label({ children }: { children: ReactNode }) {
const { pending } = useLinkStatus();
return <>{children}{pending ? " ..." : null}</>;
}
export default function Reports() {
const navigation = useNavigation();
const indicator = useLoadingIndicator({ throttle: 100 });
return (
<nav aria-busy={navigation.pending}>
<Link to="/reports" pendingClass="is-pending"><Label>Reports</Label></Link>
<progress value={indicator.progress} max={100} hidden={!indicator.isLoading} />
</nav>
);
}
Focus and the announcement
A client navigation does not reload the document, so neither the keyboard nor a screen reader learns that the page changed. Two steps do it, after the scroll.
- Focus (
app.navigation.focus,"heading"by default): moves the keyboard, without scrolling, to the#hashtarget, else an[autofocus]element, else the firsth1among the entering elements, else the firsth1of the app root, else the root, givingtabindex="-1"to one that cannot take focus and taking it off on blur."root"goes to the root,"none"moves nothing. The full rules, and when the step is skipped (keepFocus,scroll: false, a text-entry control with the focus, another query only), are in Routing. - The route announcer (
app.routeAnnouncer,{ politeness: "polite" }by default,falsefor none): writesdocument.title, else the first enteringh1, else the path, into the live region#__hamur_announcer, cleared first and set 50 ms later so the same text twice is still read. Under a view transition both steps run once the update callback finished. Nothing is announced on the first load, for another query or hash only,shallow,refreshAllorrefresh. Render<RouteAnnouncer />once to place and style the region: only one speaks.
useRouteAnnouncer().set("3 results") replaces the text of the navigation under way and announces at once at any other time. For changes inside a page (a saved form, a filter), useAnnouncer() writes into two regions that never change their aria-live, #__hamur_announcer_polite and #__hamur_announcer_assertive: polite(message), assertive(message) and set(message, politeness). <Announcer /> renders both.
import { useAnnouncer, useRouteAnnouncer } from "@hamur/adapter-react";
import { useEffect } from "react";
export default function Results({ count }: { count: number }) {
const route = useRouteAnnouncer();
const { assertive } = useAnnouncer();
useEffect(() => route.set(`${count} results`), [count]);
return (
<button type="button" onClick={() => assertive("Saved")}>
Save
</button>
);
}
Scroll
A navigation scrolls in this order: the saved position on back and forward; the #hash element; the position kept when meta.scrollToTop is false or returns false; the top. scrollToTop is true by default; as a function (to, from) => boolean it decides for a pair of pages, in a page or in a folder config for a whole section. It replaces what other frameworks call keepScroll. A scrollBehavior in app/router.options.ts replaces the rule. With a page or layout transition the scroll runs when the leave ended, with a view transition inside its update.
A scrolling element that is not the window keeps its position when it has a data-hamur-scroll-restore="<id>": it is saved with the window's position and restored on back, forward and reload (at most 16 per entry). A link that should not scroll carries scroll={false} or data-hamur-scroll="false", also on an ancestor such as a <nav>. app.navigation.scrollKey: "path" keeps positions per pathname instead of per history entry.
import type { PageMeta } from "hamur/app";
export const meta = {
scrollToTop: (to, from) => to.params.id !== from.params.id,
} satisfies PageMeta;
export default function Product() {
return (
<div>
<nav data-hamur-scroll-restore="sidebar" style={{ overflowY: "auto", height: 300 }}>Sidebar</nav>
<a href="/product/2" data-hamur-scroll="false">Next product, same position</a>
</div>
);
}
Links
Link takes these props besides to, replace, query, state, relative, mask, activeClass, exactActiveClass and ariaCurrentValue:
| Prop | What it does |
|---|---|
href | the same as to, under Nuxt's name (not in Vue); to wins when both are given |
external | a plain link: rel="external", no prefetch, never intercepted |
target, noRel | _blank or another origin gets rel="noopener noreferrer" (app.link.externalRelAttribute); noRel adds none |
prefetch, prefetchOn, noPrefetch, prefetchDelay | the prefetch |
prefetchedClass | a class the navigator adds once this link's prefetch resolved loaded or chunks |
pendingClass | the class while a navigation to it is in flight |
scroll | false keeps the scroll position |
viewTransition | true, false or { types }, see View transitions |
onBeforeNavigate(nav) | runs for a navigation this anchor started, after the component hooks; nav.cancel() stops it |
Link has no keepFocus prop: put data-hamur-keepfocus on the link or an ancestor. All the data-hamur-reload, -replace, -prefetch, -prefetch-delay, -scroll, -keepfocus and -view-transition options are read from the closest element that carries them, the anchor first, and "false" turns one off; <body data-hamur-prefetch="hover"> covers the anchors of a Markdown or CMS page, and <nav data-hamur-scroll="false"> keeps the position for its tabs.
defineLink(defaults) returns a Link with its own defaults over app.link; a prop on the element still wins. app.link takes activeClass, exactActiveClass, pendingClass, prefetchedClass, externalRelAttribute, prefetch, prefetchOn and prefetchDelay. useLink(to, options?) returns a LinkSlot, { href, attrs, active, exact, pending, navigate(event?), prefetch() }: spread attrs on your own <a> and the navigator handles its click, or call navigate(event) from any element. A children function (a scoped slot in Vue, a snippet in Svelte, a callback in html) receives the same LinkSlot and Link renders only what it returns.
<Navigate to="/new" replace /> redirects when it renders: the browser calls navigateTo once after mount; the server answers 302 with location before the body starts, or, when a stream already sent its shell, ends it with <meta http-equiv="refresh">. <Time datetime={…} /> renders a <time> with a formatted or relative text (relative, refreshed every relativeInterval ms), the same on the server and in the browser; Time has the rest.
import { Link, Navigate, defineLink, useLink } from "@hamur/adapter-react";
import type { ReactNode } from "react";
const NavLink = defineLink({ activeClass: "current", prefetchOn: "visibility" });
function ButtonLink({ to, children }: { to: string; children: ReactNode }) {
const link = useLink(to, { replace: true });
return (
<a {...link.attrs} className={link.pending ? "button busy" : "button"}>
{children}
</a>
);
}
export default function Menu() {
return (
<nav>
<NavLink to="/blog">Blog</NavLink>
<Link to="/docs" prefetchOn="render" prefetchedClass="ready">Docs</Link>
<Link to="/help" pendingClass="busy" scroll={false} onBeforeNavigate={(nav) => nav.to?.path === "/help" && console.log(nav.type)}>Help</Link>
<Link to="https://example.com" external>Example</Link>
<Link to="/tab">
{(link) => (
<button type="button" aria-pressed={link.active} onClick={(event) => void link.navigate(event)}>
Tab
</button>
)}
</Link>
<ButtonLink to="/pricing">Pricing</ButtonLink>
</nav>
);
}
export function Old() {
return <Navigate to="/new" replace />;
}
import { Time } from "@hamur/adapter-react";
export default function Post({ publishedAt }: { publishedAt: string }) {
return (
<p>
<Time datetime={publishedAt} dateStyle="long" /> (<Time datetime={publishedAt} relative relativeInterval={30_000} />)
</p>
);
}
In hamur dev, a Link whose path matches no page, no GET server route, no public/ file and no proxy, redirect or rewrite rule logs one warning per path: Link to "/abuot" matches no page or server route (rendered by app/pages/index.tsx). A production build holds neither the check nor the message.
Prefetch
A prefetch warms what a click will need. The trigger says when it starts. Each costs different requests:
| Trigger | When | What it fetches | Held back by |
|---|---|---|---|
"interaction" (default) | mouseover or focusin on the link, after prefetchDelay ms | the page's JavaScript and CSS chunks, and its load data: one request that runs the load files (and their middleware) on the server | data saver, 2g, prefers-reduced-data |
"visibility" | the link scrolls into view | the chunks only; at most 4 at a time, when the browser is idle | the same |
"render" | the link is in the page after hydration or a navigation | the chunks only, through the same idle queue | the same |
"tap" | pointerdown (touchstart without PointerEvent), about 100 ms before the click | the chunks and the data, as the click would | nothing: it is not throttled, it fetches what the click fetches |
The data is the costly part: every hover runs a load on the server, so a hover on a long list of links is a long list of requests. Choose "visibility" or "render" for chunks only, "tap" for a touch screen, a prefetchDelay so a mouse crossing a menu fetches nothing, and prefetch={false} for a link whose page has a side effect. A prefetched answer lives 30 seconds and is used once. router.prefetch(to, { data: false }) loads the chunks only (what Nuxt calls preloadRouteComponents) and always runs; it resolves to { type: "loaded", data }, { type: "redirect", location }, { type: "error", error }, { type: "chunks" } or { type: "skipped" }.
- A link to a page the browser loads as a document (a
scripts: falsepage, adata-hamur-reloadlink, a path with aredirectrule) adds one<link rel="prefetch" as="document">instead of chunks and data, once per URL. - A production build also prefetches, after the first mount and each navigation when the browser is idle, the chunks that the page on screen loads lazily with
import(), and their static dependencies, as<link rel="prefetch">, once per file, under the same data-saver rules. - In
hamur devthe visible and render triggers are off, and hover, focus and tap load chunks only, unlessdevServer.prefetchistrue. - A hand-written
<a href data-hamur-prefetch="visible">(wordshover,visible,tap,render) prefetches too, also when added after the page rendered, and so does an anchor under an element that carries the attribute.
import { Link, useRouter } from "@hamur/adapter-react";
export default function Triggers() {
const router = useRouter();
return (
<nav>
<Link to="/a">Hover or focus (default)</Link>
<Link to="/b" prefetchOn="interaction" prefetchDelay={150}>Hover, after 150 ms</Link>
<Link to="/c" prefetchOn="visibility">In view</Link>
<Link to="/d" prefetchOn="tap">Pointer down</Link>
<Link to="/e" prefetchOn="render">As soon as it is in the page</Link>
<Link to="/f" prefetchOn={{ visibility: true, interaction: true }}>In view and hover</Link>
<Link to="/g" prefetch={false}>Never</Link>
<button type="button" onClick={() => void router.prefetch("/h", { data: false })}>Chunks of /h only</button>
<a href="/i" data-hamur-prefetch="visible">A plain anchor</a>
</nav>
);
}
Speculation Rules
app.speculationRules: { prefetch?, prerender? } (default false), each "conservative", "moderate", "eager" or "immediate" or false, writes one <script type="speculationrules"> in every page document, with the request's nonce (and its hash in the policy of a hash document). It is for the links that the navigator does not take, because the browser loads those as documents:
- In a document with no client (
app.scripts: false, or a page withmeta.scripts: false), every same-origin link belowapp.baseURL. - In a document with a client, only
a[data-hamur-reload]anda[rel~="external"]belowapp.baseURL. Every other page link is a client navigation, so a speculated document would never be activated.
The rules leave out <baseURL>_hamur/*, the GET server routes, public files, proxy, redirect and rewrite rule patterns, [data-hamur-prefetch="none"], and every pattern whose route rule sets speculation: false. The browser's request carries Sec-Purpose: prefetch and the visitor's cookies, and it runs middleware and load as the click would. A page whose GET has a side effect (it counts a view, rotates a session) must not be speculated: write speculation: false in a route rule, or on the page meta.rules: { speculation: false }; the page then also gets no rules script. meta.speculation fails the build with a message that says so. A link the rules select is not prefetched by the navigator.
import type { PageMeta } from "hamur/app";
export const meta = { scripts: false, rules: { speculation: false } } satisfies PageMeta;
export default function Counter() {
return <p>This page counts a view on every GET, so the browser must not load it ahead.</p>;
}
Events
A script outside the app (analytics, a widget) listens on document. Each event is a CustomEvent that does not bubble, with detail { type, from, to, delta? }; from and to are full paths, null where the hook's are. A hash-only or shallow navigation fires none.
| Event | When | Cancelable |
|---|---|---|
hamur:beforenavigate | after onBeforeNavigate; preventDefault() is nav.cancel() | yes |
hamur:navigate | after onNavigate, before the page changes | no |
hamur:afternavigate | after onAfterNavigate, and once with type: "enter" after the first page mounted | no |
import "@hamur/adapter-react";
document.addEventListener("hamur:beforenavigate", (event) => {
if (event.detail.to?.startsWith("/admin") && !document.cookie.includes("admin=1")) event.preventDefault();
});
document.addEventListener("hamur:navigate", (event) => console.log("leaving", event.detail.from));
document.addEventListener("hamur:afternavigate", (event) => {
console.log(event.detail.type, event.detail.to);
});
Clicks during hydration
A click on a link before the page hydrated would be a full load. In an adapter whose hydration can be abandoned (React, Preact and Solid; their client entries export hydrationCanBeAborted), the first statement of the client entry holds the click, and the navigator takes it as soon as it exists: its update replaces the hydration in progress and app:mounted still runs once. In Vue, Svelte and html the click stays a document load until hydration finished.