Skip to content

Router API

This page is the reference for every public export of @rezejs/router. Use it to look up a signature, an option, or what a hook returns, and to check the defaults and rules that apply.

The createRouter factory

createRouter takes a RouterConfig and returns a RouterInstance. Render the instance as a component once, usually in the root of the app, and read its match and paths members when you need them without rendering.

import { createBrowserHistory, createRouter, defineRoutes } from "@rezejs/router";

function Home() {
  return <h1>Home</h1>;
}

function About() {
  return <h1>About the studio</h1>;
}

const routes = defineRoutes([
  { path: "/", component: Home },
  { path: "/about", component: About },
]);

export const Router = createRouter({
  routes,
  history: createBrowserHistory(),
});

RouterConfig options

OptionTypeDefaultPurpose
routesreadonly RouteDefinition[]RequiredThe route table. See route definitions.
pathsPathsTreeNoneThe paths builders. The router returns them as paths when you pass them.
historyRouterHistorycreateBrowserHistory()Where the router reads and writes the location.
linksbooleantrue for browser and hash histories, false for memoryRoutes same-origin anchor clicks that match a route through the router instead of the browser.
preloadbooleantrueRuns route preload functions when a matching link is hovered, focused, or touched.
contextCundefinedBase value of the context that route beforeLoad, preload and redirect callbacks get.

RouterContext is the default type of route callback context and is open to module augmentation. Supply its value through RouterConfig.context or a layout's beforeLoad. Augmenting the type does not create the value at runtime.

The RouterInstance members

MemberTypePurpose
call(props: { root?: (props: { children: JSX.Element }) => JSX.Element }) => JSX.ElementRenders the matched route tree. root wraps the matched output, for example to add a shell.
match(url: string) => OutputMatch[]Matches a URL without rendering. Returns [] when no route matches.
pathsPathsTree | undefinedThe paths you passed to the factory, or undefined when you passed none.
routesreadonly RouteDefinition[]The route table you passed to the factory.

Match a URL without rendering

match returns one entry per level of the matched route branch, from the outermost route to the leaf. Each entry carries the pattern and info of its own level, but path and params cover the whole URL and the whole branch, so every entry for /blog/42 reports path: "/blog/42" and params: { id: "42" }.

import { createRouter, defineRoutes } from "@rezejs/router";

const router = createRouter({
  routes: defineRoutes([{ path: "/blog", children: [{ path: "/:id" }] }]),
});

export const matches = router.match("/blog/42");

History implementations

A history decides where the router reads and writes the location. Pass one to RouterConfig.history.

FactoryBase prefixManages window scrollUse it when
createBrowserHistory(base = "")base, without a trailing slashYesThe app is served from the browser's History API at a path.
createHashHistory()#YesThe app is served where only the URL hash can change.
createMemoryHistory(initial = "/")""NoYou need a router without changing the URL, such as in tests.

Window histories save scroll positions in sessionStorage under the key reze-router:scroll, keeping at most 128 entries.

The RouterHistory interface

Each factory returns a RouterHistory. Read it when you write a custom history or inspect the one you pass in.

MemberTypePurpose
get() => HistoryEntryReturns the current entry.
push(path: string, state: unknown) => voidAdds an entry. path is a router path: pathname, search, and hash.
replace(path: string, state: unknown) => voidReplaces the current entry.
go(delta: number) => voidMoves through the session history by delta entries.
listen(listener: (entry: HistoryEntry) => void) => () => voidCalls the listener for each entry change the router did not cause, such as back and forward. Returns a remover.
resolve(url: URL) => string | undefinedReturns the router path for a same-origin anchor URL, or undefined to let the browser handle it.
basestringThe prefix that router hrefs carry.
scrollbooleanWhether the router manages window scroll for this history.

HistoryEntry has three fields: path (the router path), state (the value passed to push or replace), and index (the position in the session, so the router can tell back from forward).

Route tables

A route table is an array of RouteDefinition values passed to routes. Build it with defineRoutes so that the literal route types are kept.

Route definition fields

FieldTypePurpose
pathstringThe route pattern, relative to the parent route. Segments are static text, :param, :param?, or *splat.
componentRouteComponentRenders the route. The router passes params, location, data, and children.
childrenreadonly RouteDefinition[]Nested routes. The matched child renders through the parent's children prop.
load() => Promise<RouteModule>Loads the route module on demand. When it resolves, its default and route override component, beforeLoad, preload, redirect, info, and render.
render"static" | "server" | "client"How the page is produced. See choose a render mode per route.
idstringStable identity for server route matches and static generation. The plugin sets it for file routes. Otherwise the router assigns an index chain such as "2/0".
namestringThe key of this route in the paths builder tree. Siblings that share a key throw when the router is created.
beforeLoad(args: PreloadArgs) => Awaitable<Partial<RouterContext> | void>Extends context for this route and its descendants. See preload and redirects.
preload(args: PreloadArgs) => unknownStarts the route's data. See preload and redirects.
redirectRouteRedirect | ((args) => Awaitable<RouteRedirect | undefined>)Sends the navigation somewhere else. Its behavior is covered under Preload and redirects.
infoReadonly<Record<string, unknown>>Free-form data attached to the route. useCurrentMatches returns it for each match.

The following table defines a layout route with a nested child:

import { defineRoutes, type RouteProps } from "@rezejs/router";

function Layout(props: RouteProps) {
  return <main>{props.children}</main>;
}

function BlogIndex() {
  return <h1>Posts</h1>;
}

function BlogPost(props: RouteProps) {
  return <h1>Post {props.params.id}</h1>;
}

export const routes = defineRoutes([
  { path: "/", component: BlogIndex },
  {
    path: "/blog",
    component: Layout,
    children: [{ path: "/:id", component: BlogPost }],
  },
]);

Preload and redirects

These three fields run in a fixed order when a navigation enters a route. Page metadata is not a route field: a route component sets it with <Head>.

  • beforeLoad runs first, level by level from the root to the leaf. It receives the context built so far, and a returned object is merged over it for the route's own preload and redirect and for every route below it. Link warming runs it too, before the warmed preload.
  • preload starts the route's data. The router calls it with intent "preload" when a matching link is hovered, focused, or touched, and with intent "navigate" when the route is entered. Return a promise to start a fetch; a navigation waits for it and delivers the settled value as data, and never the promise itself.
  • redirect sends the navigation to another path. A literal object short-circuits the navigation before any preload runs. A function receives the settled data, and the first defined result from the root to the leaf wins. Hovering a link never runs redirect.

The following module loads a post's data through preload, uses it for the title, and redirects an old path:

import { defineRoutes, type RouteProps } from "@rezejs/router";
import { Head } from "reze-js";

async function loadPost(id: string) {
  return { title: `Post ${id}` };
}

function PostPage(props: RouteProps<{ id: string }, { title: string }>) {
  return (
    <>
      <Head>
        <title>{props.data.title}</title>
      </Head>
      <h1>{props.data.title}</h1>
    </>
  );
}

function NewsPage() {
  return <h1>News</h1>;
}

export const routes = defineRoutes([
  {
    path: "/posts/:id",
    component: PostPage,
    preload: ({ params }) => loadPost(params.id),
  },
  { path: "/old-news", redirect: { to: "/news", replace: true } },
  { path: "/news", component: NewsPage },
]);

preload and redirect are not limited to defineRoutes. A route module loaded through load can export the same fields as route. Its values override the definition's values once the module loads.

defineRoute and defineRoutes

defineRoutes takes an array of route definitions and returns the same array with literal types preserved. It does not change the routes at runtime.

defineRoute takes one route definition and returns it. When the definition has a preload, the returned route keeps the data type of that preload, so generated and hand-written routes can share types. Without a preload, the return type is RouteDefinition with the path kept as a literal type.

Build typed paths with buildPaths

buildPaths turns a route table into a tree of builder functions. Each builder returns a href for one route, with the parameters filled in and the search and hash appended.

import { buildPaths, defineRoutes } from "@rezejs/router";

const routes = defineRoutes([
  { path: "/", name: "index" },
  { path: "/blog/:id", name: "byId" },
]);

export const paths = buildPaths(routes);

export const postHref = paths.byId("42");
export const homeHref = paths.index();

The builder for a route takes its values in pattern order, then an optional search object and an optional hash string. The search object takes SearchInit: null and undefined values are skipped, and an array appends one entry per item. The hash must be a string, and a leading # is removed when you pass one.

In a project with generated route types, buildPaths returns the generated paths tree, so its typed keys come from the file routes rather than from the table you pass. The sample uses the keys that the generated routes in this project define.

RuleBehavior
Key of a route in the treeThe route's name when you set one. Otherwise a static last segment keeps its text, and a parameter or splat becomes by plus the capitalized name, such as byId or byRest.
Multi-segment pathThe key comes from its last segment, so "/tags/*rest" under blog is paths.blog.byRest.
Splat valuesA string is split on /. An array gives one segment per item. Each value is encoded with encodeURIComponent.
Missing parameterThrows [reze-router] paths.blog.byId requires a value for ":id", naming the route's position in the tree.
Duplicate keys under one parentThrows [reze-router] duplicate path name "<key>" under "<trail>"; rename a segment when the builders are created.

Keys that are not valid identifiers, such as about-us, are read with bracket notation, as in paths["about-us"].

With the Vite plugin, the same builders come from generated route files, typed by Register. See generated route types.

Hooks

Each hook must run inside a component, because it reads the router from the component's context. The reactive getters the hooks return update when the location changes.

Read the location and params

useLocation returns a getter for the current Location. useParams returns a getter for the params of the matched route, and it accepts a route pattern to type those params in generated apps.

import { useLocation, useParams } from "@rezejs/router";

export function PostHeader() {
  const params = useParams();
  const location = useLocation();

  return (
    <header>
      <p>Post {params().id}</p>
      <p>{location().pathname}</p>
    </header>
  );
}

Location has pathname, search, hash, query, and state. The query field maps each key to a string, or to an array of strings when the key repeats, such as ?tag=a&tag=b.

Read matches and routing state

useCurrentMatches returns a getter for the matched routes, from the root to the leaf. Each RouteMatch has path, params, data, and info. useIsRouting returns a getter that is true while a navigation waits for route modules to load.

import { useCurrentMatches, useIsRouting } from "@rezejs/router";

export function Breadcrumbs() {
  const matches = useCurrentMatches();
  const routing = useIsRouting();

  return (
    <nav>
      <p>{routing() ? "Loading" : "Ready"}</p>
      {matches().map((match) => (
        <span>{match.path}</span>
      ))}
    </nav>
  );
}

useNavigate returns a Navigate function. Its to argument is one of three kinds of value:

  • A number moves through the history by that many entries, as history.go does.
  • A route path, with an optional query or hash, is resolved against the current location.
  • An absolute URL outside the router is loaded with location.assign.

The options object takes replace, state, and scroll. scroll defaults to true, which scrolls to the hash target or the top of the page after the navigation.

import { useNavigate } from "@rezejs/router";

export function SaveButton() {
  const navigate = useNavigate();

  return <button onClick={() => navigate("/blog/42", { replace: true })}>Save</button>;
}

Read and write search parameters

useSearchParams returns a tuple of a getter for the query and a setter. The setter merges its SearchInit argument into the latest location, so keys you omit keep their values. A null or undefined value deletes a key, and an array value appends one entry per item. The setter scrolls to neither the hash nor the top by default, because its default options are { scroll: false, ...options }.

import { useSearchParams } from "@rezejs/router";

export function TagFilter() {
  const [, setQuery] = useSearchParams();

  return <button onClick={() => setQuery({ tag: ["ui", "forms"], page: null })}>Filter</button>;
}

Guard navigation with useBeforeLeave

useBeforeLeave registers a listener that runs before each navigation away from the current path, and before the document unloads. The listener is removed when the component that called the hook is disposed.

The listener receives a BeforeLeaveEvent:

MemberTypePurpose
fromLocationThe location you are leaving.
tostring | number | nullThe target path, a history delta, or null when the document is unloading.
optionsNavigateOptionsThe options of the navigation.
defaultPreventedbooleanWhether an earlier listener blocked the navigation.
preventDefault()() => voidBlocks the navigation. For a document unload, the browser shows its own confirmation.
retry(force?)(force?: boolean) => voidRuns the blocked navigation again. force defaults to true and skips the leave guards. It does nothing for a document unload.

The router skips the listener when the target path equals the current path. A listener that throws is reported with reportError, and the navigation continues.

import { useBeforeLeave } from "@rezejs/router";

export function Editor() {
  useBeforeLeave((event) => {
    if (!window.confirm("Discard your changes?")) event.preventDefault();
  });

  return <textarea />;
}

A link is an <a> element whose href matches a route. The router routes its clicks through the history, and it can preload the route's data on hover, focus, or touch.

Anchor attributes

Anchors take these attributes in addition to href:

AttributeTypeEffect
hrefHrefThe destination. Typed against the generated route paths.
replacebooleanReplaces the current entry instead of adding one.
noscrollbooleanSkips the scroll after the navigation.
statestringPassed to the navigation as its state.

The router handles a click only when the href matches a route and the click has no modifier keys and is not already prevented. Any other anchor is left to the browser.

The compiler reports a bare state attribute as UNKNOWN_ATTRIBUTE, so write it as attr:state, as the sample does. The router reads the attribute under the name state.

export function PostLinks() {
  return (
    <nav>
      <a href="/blog/42" replace={true}>
        Post 42
      </a>
      <a href="/" noscroll={true} attr:state="from-nav">
        About
      </a>
    </nav>
  );
}

useLinkState

useLinkState takes a getter for an Href and returns a LinkState for it. Each member is a getter that returns a boolean.

MemberTypeMeaning
current() => booleanThe link's pathname is the current pathname. The link gets aria-current="page".
active() => booleanThe link's pathname is the current pathname or a segment prefix of it. / is active only when it matches exactly. The link gets data-active.
pending() => booleanA navigation to exactly the link's pathname waits for route modules. The link gets data-pending.
import { useLinkState, type Href } from "@rezejs/router";

export function NavLink(props: { href: Href; label: string }) {
  const state = useLinkState(() => props.href);

  return (
    <a href={props.href} data-state={state.pending() ? "pending" : "idle"}>
      {props.label}
    </a>
  );
}

link(el, href?) attaches the link state described above to an element and routes its clicks through the router. With the Vite plugin's links option on, the compiler passes each <a href> it claims to link, so you rarely call it yourself. The compiler does not claim an anchor that sets aria-current itself.

Generated route types

The Vite plugin generates types for the routes in a project and attaches them to @rezejs/router through the Register interface. Each generated type falls back to a loose type when the plugin does not generate one.

The Register interface

The generated declaration augments Register with four members:

  • paths: every href shape of every leaf route. RoutePath, Href, and NavigateTarget read it.
  • base: the prefix an <a href> gets, or # for hash history.
  • routes: each leaf pattern mapped to its params and data. ParamsFor and DataFor read it.
  • pathsTree: the typed paths builders. PathsTree reads it.

The plugin writes the declaration to src/routes.gen.d.ts by default. You do not write Register by hand. Without generated types, RoutePath is string, RoutePattern is string, and the params and data types fall back to Params and unknown.

Route module types

A route module in src/routes/ can type its route export and its component props from its own pattern. RouteConfigFor checks the render, beforeLoad, preload, redirect, and info fields against the leaf pattern, and RoutePropsFor gives the component typed params and data.

import type { RouteConfigFor, RoutePropsFor } from "@rezejs/router";

export const route = {
  preload: ({ params }) => ({ title: `Post ${params.id}` }),
} satisfies RouteConfigFor<"/blog/:id", { title: string }>;

export default function BlogPost(props: RoutePropsFor<"/blog/:id">) {
  return <h1>{props.data.title}</h1>;
}

Href types

Href is the type of an <a href>. NavigateTarget is the type of a navigate target, which omits the base prefix. HrefFor expands one route shape into its plain, query, and hash forms.

import type { Href } from "@rezejs/router";

export const featuredPost: Href = "/blog/42";

export default function Home() {
  return <h1>Home</h1>;
}

Route parameter types

RouteParams parses a pattern string into an object type of its parameters. An optional segment, such as :id?, types as string, as Params does.

import type { RouteParams } from "@rezejs/router";

export type BlogParams = RouteParams<"/blog/:id/*rest">;

For file routes, the Vite plugin's fileRoutes option controls the route directory, the generated declaration path, and the links behavior. Its options are listed on the Vite plugin page.

Other exported types

These exports are types only. They describe values you receive from the hooks, the builders, and the route definitions.

TypeShape or meaning
AnchorAttributesThe attributes an <a> element accepts, listed in anchor attributes.
Awaitable<T>T or a promise-like of T.
DataFor<P>The data type of leaf pattern P, or unknown without generated types.
DataOf<M>The awaited return of a route module's route.preload, or unknown.
HistoryEntry{ path, state, index } as described in the RouterHistory interface.
HrefAn <a href> value. Any string without generated types.
HrefFor<H>H, H with a query, or H with a hash.
LinkStateThe return type of useLinkState, as described in useLinkState.
Location{ pathname, search, hash, query, state }.
LoosePathNode, LoosePathsThe builder types used when no generated pathsTree exists.
NavigateThe type of the function useNavigate returns.
NavigateOptions{ replace?, state?, scroll? }.
NavigateTargetA navigate target: a route path, a path with a query or hash, or an absolute URL.
OutputMatch{ path, pattern, params, info }, the entries match returns.
ParamsA readonly record of string params.
ParamsFor<P>The params of leaf pattern P, or Params without generated types.
PathMatch{ params, path }, the result of matching one pattern. No hook in this version returns it.
PathMatchFor<P>{ params, path } typed by the pattern P. No hook in this version returns it.
PathsTreeThe type of the paths builders: generated, or LoosePaths otherwise.
PreloadArgs<P, C>{ params, location, intent, context }, the argument of preload. intent is a PreloadIntent.
PreloadIntent"initial", "navigate", or "preload".
RegisterThe interface the generated declaration augments.
RouteComponent<P, D>A component that receives RouteProps<P, D> and returns a JSX.Element.
RouteConfig<D, C>The beforeLoad, preload, redirect, info, and render fields of a route.
RouteConfigFor<P, D, C>RouteConfig with the params of leaf pattern P and context C.
RouteDefinition<C>RouteConfig plus path, id, name, component, load, and children.
RouteMatch{ path, params, data, info }, the entries useCurrentMatches returns.
RouterContextThe augmentable default type of the route callback context.
RouteModule<C>{ default?, route? }, the module a load function resolves to.
RouteParams<S>The params parsed from pattern string S.
RoutePathEvery href path, or string without generated types.
RoutePatternEvery leaf pattern, or string without generated types.
RouteProps<P, D>{ params, location, data, children }, the props a route component receives.
RoutePropsFor<P>RouteProps with the params and data of leaf pattern P.
RouteRedirect{ to, replace? }, the value a redirect resolves to.
RouteResolvedArgs<P, D, C>PreloadArgs plus the settled data, the argument of a redirect function.
SearchInitA record of search values, where an array value appends one entry per item.
SearchValuestring, number, boolean, null, or undefined.
BeforeLeaveEventThe event described in guarding navigation.
RouterConfigThe options described in RouterConfig options.
RouterInstanceThe members described in the RouterInstance members.
  • Routing explains file routes, layouts, params, data, and navigation in an app.
  • Vite plugin covers the fileRoutes option and the generated declaration.
  • Installation covers project setup and the first component.
  • Components covers props and children for route components.
  • Lifecycle covers cleanup of the listeners that hooks register.
  • Compiler covers how the compiler claims anchors and lowers reactive reads.