Skip to content

Routing

Reze turns the files under src/routes into routes. This page covers the file conventions, layouts, params, typed paths, data loading, redirects, navigation, link handling, search params, and deployment. For the createRouter options, histories, and hook signatures, see the Router API.

Set up file routes

Install the packages as described in Installation. Then turn on file routes in the Vite config:

import reze from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [reze({ fileRoutes: true })],
});

The Vite plugin reads src/routes and generates the virtual:reze-routes module. That module exports routes and paths. Pass both to createRouter, choose a history, and render the router with a shell component that wraps every page:

import { createBrowserHistory, createRouter } from "@rezejs/router";
import { render } from "reze-js";
import { paths, routes } from "virtual:reze-routes";

import { Shell } from "./Shell";

const Router = createRouter({ routes, paths, history: createBrowserHistory(import.meta.env.BASE_URL) });

render(() => <Router root={Shell} />, document.getElementById("app")!);

The shell renders around each page. It links to the home page, so the project needs src/routes/index.tsx:

import { useIsRouting } from "@rezejs/router";
import type { JSX } from "reze-js";
import { paths } from "virtual:reze-routes";

export function Shell(props: { children: JSX.Element }) {
  const isRouting = useIsRouting();
  return (
    <>
      <nav>
        <a href={paths.index()}>Home</a> <a href={paths.about()}>About</a> <a href={paths.blog()}>Blog</a>
        {isRouting() ? <span id="routing"> loading</span> : null}
      </nav>
      <main>{props.children}</main>
    </>
  );
}
export default function Home() {
  return <h1>Home</h1>;
}

Map files to URLs

Each file under src/routes becomes a route. Folders add URL segments, and file names add params:

FileRoute pattern
src/routes/index.tsx/
src/routes/about.tsx/about
src/routes/blog/index.tsx/blog
src/routes/blog/[id].tsx/blog/:id
src/routes/blog/[[page]].tsx/blog/:page?
src/routes/docs/[...slug].tsx/docs/*slug
src/routes/(auth)/login.tsx/login

The scanner applies these rules:

  • An index file serves the URL of its folder. blog/index.tsx serves /blog.
  • [name] is a required param. [[name]] is an optional param, so the URL matches with or without that segment.
  • [...name] is a catch-all. It matches one or more segments, and it must be the last segment of its path.
  • (group) folders add no URL segment. Use them to organize files.
  • A file whose name matches its folder is that folder's layout. See Add layouts.
  • Files and folders whose names start with _ or . are skipped. So are *.d.ts, *.test.*, and *.spec.* files.

When more than one route matches a URL, the router compares the segments from left to right. A static segment beats a param, a param beats a catch-all, and the route defined first wins a tie. Static segments match case-insensitively. Trailing slashes and empty segments are ignored.

Scan errors

The plugin stops the build when the route files cannot form a valid route tree. The errors include:

  • Two files resolve to the same route.
  • Two routes with conflicting shapes match the same URL. The message names both routes, for example routes "<a>" and "<b>" both match.
  • A catch-all is not the last segment.
  • A param name is invalid or repeated in one path.
  • An optional param comes before a required segment.
  • The routes directory does not exist. The message is [reze-router] routes directory not found: <dir>.

Add layouts

A route module with a default export renders a page. A module without a default export renders its children, which makes it a layout. Layouts share their markup with every route nested under them. This file in src/routes/blog.tsx wraps every page under /blog:

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

export default function BlogLayout(props: RouteProps) {
  return (
    <section>
      <h2>Blog</h2>
      {props.children}
    </section>
  );
}

The pages in src/routes/blog/ render in place of the layout's children.

The server sends a layout with the page it wraps. On navigation between server-rendered pages, a layout that the next page renders the same way keeps its DOM, so its scroll, open menus and island state survive. See Keep layout state across navigation.

Read params

A dynamic route receives its params through RouteProps for the page component, or through useParams anywhere below the route. A catch-all's value is stored under the name of the catch-all:

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

export default function NotFound(props: RouteProps<{ "404": string }>) {
  return <p>No page at /{props.params["404"]}</p>;
}

Dynamic values are decoded with decodeURIComponent. A value that cannot be decoded is kept as written.

useParams() returns a getter for the params of the deepest matched route, merged with the params of its layouts. Pass a route pattern to type the result. This component reads the id of /blog/:id from any place under that route:

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

export function PostHeader() {
  const params = useParams("/blog/:id");
  return <h1>Post {params().id}</h1>;
}

A URL that matches no route renders nothing. Add a catch-all route to render a not-found page.

Build typed paths

The plugin generates paths, one builder per route. A builder takes the route's params in order, then an optional search object and an optional hash string, and returns an href that includes the router base:

import { paths } from "virtual:reze-routes";

export function PostLinks() {
  return (
    <nav>
      <a href={paths.blog.byId(1)}>First post</a>
      <a href={paths.blog.byId(2, { tab: "comments" }, "#replies")}>Comments</a>
    </nav>
  );
}

The builders follow these rules:

  • Param values are encoded with encodeURIComponent.
  • In search, a null or undefined value is skipped. An array appends one entry for each non-nullish item.
  • A leading # in hash is optional. The builder adds one when it is missing.
  • A catch-all builder takes a string or an array of segments.
  • Hash routing changes the base to #, so paths.about() returns #/about. See Host a client-only build.
  • A builder that needs a required param throws when the value is missing, for example [reze-router] paths.blog.byId requires a value for ":id".

A folder with two dynamic children, such as [id].tsx and [slug].tsx, has no unambiguous href. The builder for that folder throws. Nest the dynamic segments in separate folders, so each level has one dynamic child.

Load data before rendering

A route can export route with a preload function. The router runs preload before it commits the page, so the component reads the loaded data through props.data:

import type { RouteConfigFor, RoutePropsFor } from "@rezejs/router";
import { paths } from "virtual:reze-routes";

interface Post {
  title: string;
}

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

export default function PostPage(props: RoutePropsFor<"/blog/:id">) {
  return (
    <article>
      <h2>{props.data.title}</h2>
      <p>id: {props.params.id}</p>
      <a href={paths.blog.byId(Number(props.params.id) + 1)}>Next post</a>
    </article>
  );
}

The router calls preload with an intent that tells it why the page loads:

  • initial runs for the first page the app renders.
  • navigate runs when the user navigates to the route.
  • preload runs when the router warms the route for a link. See Hover warming.

While a navigation waits for preload, the current page stays on screen, and useIsRouting() returns true. Show pending state and errors describes the pending state.

A navigation that changes only the hash, such as /about to /about#intro, skips preload.

Hover warming

With preload enabled, which is the default, the router starts loading a route before the user clicks one of its links:

  • Hovering a link starts a 20 ms timer. When the timer ends, the router loads the route's chunk and runs its preload with intent preload. Moving the pointer away before the timer ends cancels the warming.
  • Focusing a link, or touching it, starts warming at once.
  • Warming never runs a redirect function or renders the route.
  • An error during warming is ignored. The navigation runs preload again and reports the error if it repeats.
  • A navigate call made while warming is running a preload is ignored.

Set preload: false in createRouter to turn warming off. Clicks still route the page.

Share context with child routes

A layout's beforeLoad returns values for every route below it. The router runs beforeLoad from the root to the leaf before each level's preload, and merges each returned object into the context that the level's own preload and redirect and all deeper routes receive. It runs wherever preload runs: in the browser for a client-only app, and on the server with ssr or ssg:

import type { PreloadArgs } from "@rezejs/router";
import type { JSX } from "reze-js";

declare module "@rezejs/router" {
  interface RouterContext {
    locale: string;
  }
}

export const route = {
  beforeLoad: ({ location }: PreloadArgs) => ({ locale: String(location.query.lang ?? "en") }),
};

export default function Account(props: { children: JSX.Element }) {
  return <section>{props.children}</section>;
}

A route under src/routes/account/ reads it as context.locale in preload or redirect. With ssr, the context starts from the value the server passes to the handler, as Pass request values to routes shows. Read cookies and headers there, since beforeLoad sees only the URL.

A production build leaves the beforeLoad code out of the bundle when no file in the project mentions beforeLoad. If a dependency then defines a beforeLoad, the build stops with a message to declare that route config in the app's own sources.

Set page metadata

Page metadata lives in <Head>, inside the components that render the page. src/document.tsx gives the defaults, and each shell, layout and route component overrides them for its part of the tree:

import { Head } from "reze-js";

export default function About() {
  return (
    <>
      <Head>
        <title>About</title>
        <meta name="description" content="Who we are" />
        <link rel="canonical" href="https://site.example/about" />
        <script src="https://cdn.example.test/widget.js" async />
      </Head>
      <h1>About</h1>
    </>
  );
}

Values can be dynamic, such as <title>{props.data.title}</title> with the data from preload, and the tag follows them.

Each head tag has a key: <title> and <base> are their own keys, a <meta> is keyed by its name, property or http-equiv, <link rel="canonical"> by its rel, any other <link> by rel plus href, and a <script> by src. While a component is mounted, its tag replaces the tag with the same key from src/document.tsx or from an outer component, so the deepest route wins. Leaving the route shows the replaced tag again, down to the document's own tag. Tags without a key, such as <style> or a JSON-LD <script>, add to the head instead.

The rule is the same everywhere: the browser applies it on every navigation, and the server applies it to SSR and SSG pages, so the first byte already carries the route's title.

Redirect routes

A route can send the user to another path. Export redirect from route. It is either an object or a function that receives the route's params:

import type { RouteConfigFor } from "@rezejs/router";
import { paths } from "virtual:reze-routes";

export const route = {
  redirect: ({ params }) => ({ to: paths.blog.byId(params.id) }),
} satisfies RouteConfigFor<"/legacy/:id">;

These rules apply to redirects:

  • The router checks object redirects from every matched route before it runs any preload. Then it checks each matched route, from the root to the leaf: preload, then the redirect function.
  • A redirect function that returns undefined or null keeps the page. The first redirect that returns a value, checked from the root to the leaf, wins.
  • A redirect replaces the current history entry unless you set replace: false.

The redirects in a prerendered build have extra rules. See Prerender pages.

Use useNavigate() to change pages from an event handler. Its first argument is a path, an absolute URL, or a number of history steps:

import { useNavigate } from "@rezejs/router";
import { paths } from "virtual:reze-routes";

export function PostButtons() {
  const navigate = useNavigate();
  return (
    <div>
      <button onClick={() => navigate(paths.blog())}>Back to list</button>
      <button onClick={() => navigate(-1)}>Previous page</button>
      <button onClick={() => navigate(paths.blog.byId(2), { replace: true, scroll: false })}>Next post</button>
    </div>
  );
}

The options are:

  • replace replaces the current history entry instead of adding one. Navigating to the path that is already current also replaces it.
  • state stores a value on the history entry. Read it with useLocation().state.
  • scroll defaults to true. Set it to false to keep the scroll position.

A path routes inside the app. An absolute URL outside the router base loads in the browser. A number moves through the history by that many steps, like history.go.

Scrolling works as follows. Back and forward navigation restore the saved scroll position. A navigation to a hash scrolls the matching element into view. Any other navigation scrolls to the top, unless it is the initial render or scroll is false. Only histories that control scrolling do this. Browser and hash histories control scrolling, and memory history does not.

Anchors that point to routes do not need a router component. Write a native <a href> with a path from paths:

import { paths } from "virtual:reze-routes";

export function Nav() {
  return (
    <nav>
      <a href={paths.index()}>Home</a>
      <a href={paths.about()}>About</a>
      <a href={paths.blog.byId(1)} replace noscroll>
        First post
      </a>
    </nav>
  );
}

The anchor attributes are:

  • replace replaces the history entry, as the replace option does for navigate.
  • noscroll keeps the scroll position, as scroll: false does.

With fileRoutes enabled, the compiler claims an <a> element when all of these hold:

  • The element has an href attribute, and a spread does not override that attribute.
  • The element has no aria-current attribute.
  • The href is routable.

A routable href is a path inside the app. The compiler does not claim these hrefs:

  • Query-only hrefs such as ?tab=2.
  • Protocol-relative hrefs such as //example.com.
  • Fragment hrefs such as #intro. A hash route such as #/about is routable.
  • Any URL with a scheme, such as https: or mailto:.

A literal null or false href is not claimed. An expression is claimed, because its value is unknown until runtime.

Set fileRoutes.links to false in the Vite plugin to turn claims off. The links option of createRouter is a separate setting, described next.

Click handling

The router intercepts clicks on routable anchors when the links option of createRouter is on. The default is true for browser and hash histories and false for memory history.

The browser handles a click, and the router does not, when any of these hold:

  • The click was already prevented with preventDefault.
  • The button is not the primary button.
  • The user holds Meta, Control, Shift, or Alt.
  • The anchor has a download attribute, or a target other than _self.
  • The anchor has a rel value that contains external.
  • The URL is cross-origin or outside the history base.
  • No route matches the URL.

A claimed link gets attributes that reflect the current location:

  • aria-current="page" when the link's path is the current path.
  • data-active when the link's path is the current path or a parent of it, matched by segment. The / link is active only on /.
  • data-pending while a navigation to the link's path is loading route modules or async preload data.

Code can read the same state. The useLinkState hook returns getters for current, active, and pending. The Router API lists the link function and useLinkState signatures.

Show pending state and errors

useIsRouting() returns a getter. It is true before the first commit, and while a navigation waits for route modules or async preload data. It becomes false when the new page commits. Hover warming does not change it.

An error thrown during a route's preload or redirect is rethrown when the page renders. The nearest catchError boundary handles it. See Lifecycle for how boundaries work.

When a route module fails to load, the page renders the load error. The next navigation to that route tries to load the module again.

Guard leaving a page

useBeforeLeave registers a listener that runs before the router leaves the current page. The listener is removed when its owner is disposed. The listener receives an event with these fields:

  • from and to are the current and target locations.
  • options are the navigation options, such as replace.
  • defaultPrevented tells whether a listener already prevented the navigation.
  • preventDefault() cancels the navigation.
  • retry(force = true) runs the navigation again. With force set, the guards do not run again.

This editor blocks navigation while it has unsaved changes, and it resumes the navigation after the user saves:

import { type BeforeLeaveEvent, useBeforeLeave } from "@rezejs/router";

let hasUnsavedChanges = false;
let pendingNavigation: BeforeLeaveEvent | undefined;

export function saveDraft() {
  hasUnsavedChanges = false;
  const event = pendingNavigation;
  pendingNavigation = undefined;
  event?.retry();
}

export function Editor() {
  useBeforeLeave((event) => {
    if (!hasUnsavedChanges) return;
    event.preventDefault();
    pendingNavigation = event;
  });
  return (
    <textarea
      rows={12}
      onInput={() => {
        hasUnsavedChanges = true;
      }}
    />
  );
}

These rules also apply:

  • A navigation to the current path skips the guards.
  • Back and forward navigation that a guard blocks returns the history to the page the user was on.
  • While a leave listener is registered in a browser page, the router installs a beforeunload listener. It removes that listener when the last leave listener is removed.
  • A listener that throws reports the error and does not block the navigation.

Read and set search params

useSearchParams() returns a getter and a setter. The getter reads the query of the committed location. A key that repeats in the URL reads as an array:

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

export default function BlogIndex() {
  const [search, setSearch] = useSearchParams();
  const tab = () => {
    const value = search().tab;
    return typeof value === "string" ? value : "latest";
  };
  return (
    <div>
      <button onClick={() => setSearch({ tab: "popular" })}>Show popular posts</button>
      <p>Tab: {tab()}</p>
    </div>
  );
}

The setter follows these rules:

  • It builds the new query from the latest navigation, including a navigation that is still loading.
  • A null or undefined value deletes the key.
  • An array replaces every value for the key. The key moves to the end of the query. Each null or undefined item is skipped.
  • An empty array deletes the key.
  • A scalar value replaces the key's values.
  • It pushes a history entry by default. Set replace: true to replace the entry instead.
  • It does not scroll by default.

useLocation() returns a getter for the committed location. The Location object has pathname, search, hash, query, and state. Read the getter inside the code that needs the current value.

Deploy the router

A Reze router app deploys in one of three ways. You can render each request on a server with ssr, prerender each route to its own HTML file, or host a client-only build. Server rendering describes the first. Prerendering gives each route a document the server can return before the script runs. A client-only build needs the host to serve index.html for every route.

Prerender pages

Set ssg in the Vite plugin options. ssg: true takes every default. The plugin prerenders the file routes in src/routes, and turns fileRoutes on when it is not set. The paths option lists the params for each dynamic route:

import reze from "@rezejs/vite-plugin";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    reze({
      ssg: {
        paths: {
          "/blog/:id": [{ id: "1" }, { id: "2" }],
        },
      },
    }),
  ],
});

There is no entry module. The plugin renders the file routes into the document, which holds the markup every page shares.

The ssg options are:

  • document is the document module that each page is written into. It defaults to src/document.tsx.
  • trailingSlash is "always" by default. With "always", /about is written to /about/. With "never", it stays /about. Each page is written to an index.html in its folder.
  • timeoutMs limits how long the build waits for the route discovery step and for each page to render. It defaults to 30000.
  • paths maps each route pattern to its params. The value is an array of param records, or a function that returns the array, synchronously or as a promise. A param value is a string, an array of strings, or undefined.

Every dynamic route needs an entry in paths. Map a route to [] to skip it. A static route must not have an entry, because it renders once. An entry for an unknown pattern or an unknown param name is an error, and so is a page whose output file collides with another page's.

Prerendering rejects these setups:

  • fileRoutes.history: "hash", because hash routes have no server path to render.
  • fileRoutes: false, because the pages are the file routes.
  • Library builds, build.watch builds, and explicit Vite build.ssr builds.
  • A redirect to a path under the base that does not match a prerendered page, or to a path outside the base.
  • A redirect to a URL with a scheme other than http: or https:. Absolute http: and https: targets, and protocol-relative // targets, are left as they are.
  • A cycle of redirects.

With ssr or ssg set, the browser does not run the route table. A click on a link to another page of the app fetches that page's HTML and replaces the content of the mount element, then updates the address bar and the <Head> tags of the new page. Nothing else in the document reloads, so state outside the mount element survives. Everything inside the mount element is new, including the DOM of a layout that appeared on both pages.

  • beforeLoad, preload and redirect run on the server for each request, or once for each page at build time. They do not run in the browser. A component receives the result through props.data.
  • Hovering, focusing, or touching a link fetches its page ahead of the click, once for each link within 10 seconds. useIsRouting() is true while a navigation waits for its page.
  • A response that is not HTML, a failed fetch, or a build ID that differs from the current page's loads the destination as an ordinary navigation.
  • useLocation, useParams, useNavigate, useSearchParams, useIsRouting, useBeforeLeave, and link work inside islands. useCurrentMatches returns each match's path and params, and data is undefined there.

Host a client-only build

A build without ssg is a client-only single-page app. The browser reads the URL, so the host must serve index.html for every route path. Most static hosts have a rewrite rule for this.

If the host cannot rewrite paths, use hash routing. Set fileRoutes to { history: "hash" }, so the generated paths hrefs start with #/. Then create the router with createHashHistory():

import { createHashHistory, createRouter } from "@rezejs/router";
import { render } from "reze-js";
import { paths, routes } from "virtual:reze-routes";

import { Shell } from "./Shell";

const Router = createRouter({ routes, paths, history: createHashHistory() });

render(() => <Router root={Shell} />, document.getElementById("app")!);

Hash routing cannot be combined with ssg.

  • For the createRouter options, histories, hooks, and route types, see the Router API.
  • For the file-route and prerendering options of the Vite plugin, see the Vite plugin.
  • For error boundaries, see Lifecycle.
  • For how the compiler claims links, see Compiler.
  • For installing the packages, see Installation.