@k8ordo/router

API

The functions, components and types @k8ordo/router exports.

On this page

defineRoutes

Import from @k8ordo/router

Creates the route table. Each key is a path pattern, and each value is a page component or an object with children.

ts
defineRoutes<R extends RoutesRecord>(record: R): Routes<R>

Parameters

recordRoutesRecord
The route table. Every key is a pattern starting with /.

Returns

Routes<R> — An object holding the table as passed and match, which matches a path against it.

Caveats

  • The table is checked when this is called. A mistake in it, such as a key not starting with / or a pattern declared twice, is a TypeError. The message reads like route pattern "/x" is declared twice.
  • Patterns are tried in the order written, and the first that fits wins. Put /* last.
routes.ts
export const routes = defineRoutes({
  '/': Home,
  '/products': {
    layout: ProductsLayout,
    children: { '/': ProductList, '/:id': ProductPage },
  },
  '/*': NotFound,
});

Router

Import from @k8ordo/router

Connects the route table to the Navigation API and renders the page that fits the current path. Put it once, at the top of an app that renders in the browser.

ts
<Router routes={Routes} />

Parameters

routesRoutes
The route table defineRoutes returned.

Caveats

  • It handles only navigations to paths the table matches. The rest is left to the browser.
  • Opened at a path the table does not match, it renders nothing.
  • It reads the browser’s URL when it mounts, so it cannot render on the server.

Outlet

Import from @k8ordo/router

Marks where, inside a layout, the page it wraps is rendered.

ts
<Outlet />

Caveats

  • Rendered outside <Router>, it throws Outlet must render inside <Router>. Under @k8ordo/framework, a layout renders children instead.

href

Import from @k8ordo/router

Builds the URL a link points at from a pattern and its params.

ts
href<P extends RegisteredNavigablePattern>(
  pattern: P,
  params?: RegisteredParams<P>,
): string

Parameters

patternP
The pattern to link to. With Register augmented, only the table’s linkable patterns are accepted.
paramsRegisteredParams<P>
The values of the pattern’s params. Left out for a pattern without params.

Returns

string — A URL for an <a>’s href attribute, with Vite’s base prepended.

Caveats

  • Values are encoded with encodeURIComponent.
  • At run time, a pattern with /* throws a TypeError containing is a wildcard. A param without a value throws one containing needs a value for, and a value that cannot be spelled in a URL one containing has no URL spelling.
ts
href('/products'); // '/products'
href('/products/:id', { id: 42 }); // '/products/42'

Import from @k8ordo/router

Builds a URL from a pattern and its params, and navigates there.

ts
navigateTo<P extends RegisteredNavigablePattern>(
  pattern: P,
  params?: RegisteredParams<P>,
  options?: NavigateToOptions,
): NavigationResult

Parameters

patternP
The pattern to link to. With Register augmented, only the table’s linkable patterns are accepted.
paramsRegisteredParams<P>
The values of the pattern’s params. Left out for a pattern without params.
optionsNavigateToOptions
Options for the navigation. For a pattern without params, it is the second argument.

Returns

NavigationResult — The { committed, finished } that navigation.navigate() returns. finished resolves once the new page is on screen.

Caveats

  • By default, it adds a new history entry.
  • Overtaken by another navigation, finished rejects with an AbortError.
ts
await navigateTo('/products/:id', { id: '42' }).finished;
navigateTo('/products', { history: 'replace' });

bindParams

Import from @k8ordo/router

Creates an href and a navigateTo that fill in some params from a function. Use it for a param every link shares, such as a locale.

ts
bindParams<const Bound extends BoundParams>(
  source: () => Bound,
): BoundLinks<Bound>

Parameters

source() => Bound
A function returning the params to fill in. It is called on every call to href or navigateTo.

Returns

BoundLinks<Bound> — An href and a navigateTo that fill in what source returns.

Caveats

  • A param source supplies may be left out. Passing it overrides the value.
  • When the pattern names a param, the options are always the third argument. When source supplies every param, pass undefined as the second.

usePathname

Import from @k8ordo/router

Returns the path the browser is on.

ts
usePathname(): string

Returns

string — The current path, without Vite’s base or a trailing slash.

Caveats

  • It re-renders only when the path changes, never when only the query does.
  • It changes as soon as the URL does, without waiting for the new page to be on screen.
  • In a server render, it works only in a page @k8ordo/framework renders. During hydration, it also works under <Router>. Elsewhere it throws an error starting with usePathname needs <Router> above it.
  • Below <BrowserPathname>, a server render returns no path and waits for the browser.

useMatch

Import from @k8ordo/router

Checks whether the current path fits a pattern.

ts
useMatch<P extends MatchablePattern>(
  pattern: P,
  options?: MatchOptions,
): ParamsOf<P> | null

Parameters

patternP
A pattern from the table, or one followed by /*. /* fits the paths below that pattern.
optionsMatchOptions
With inclusive set to true, a /* pattern also fits its own page.

Returns

ParamsOf<P> | null — The params when it fits, or null.

Caveats

  • Built on usePathname, it re-renders only when the path changes.
  • It needs no route table, so it also works in pages under @k8ordo/framework.

matchPath

Import from @k8ordo/router

Makes the same check as useMatch, against the path you pass.

ts
matchPath<P extends MatchablePattern>(
  pattern: P,
  pathname: string,
  options?: MatchOptions,
): ParamsOf<P> | null

Parameters

patternP
A pattern from the table, or one followed by /*. /* fits the paths below that pattern.
pathnamestring
The path to check. A trailing slash is dropped before comparing.
optionsMatchOptions
With inclusive set to true, a /* pattern also fits its own page.

Returns

ParamsOf<P> | null — The params when it fits, or null.

ts
matchPath('/products/:id', '/products/42'); // { id: '42' }
matchPath('/products/*', '/products'); // null
matchPath('/products/*', '/products', { inclusive: true }); // {}

usePendingPathname

Import from @k8ordo/router

Returns the path of the page being loaded.

ts
usePendingPathname(): string | null

Returns

string | null — The path of the page being loaded, or null when none is.

Caveats

  • It is set as a navigation starts. It goes back to null once the new page is on screen. An abandoned navigation or a failed load also resets it.
  • A navigation that changes only the query sets nothing, unless the page loads again for it.
  • It is null in a server render.

useParams

Import from @k8ordo/router

Reads a page’s params, typed by its pattern.

ts
useParams<P extends RegisteredPattern>(pattern: P): ParamsOf<P>

Parameters

patternP
The pattern of the page this component is rendered under.

Returns

ParamsOf<P> — The params, typed by the pattern. Every value is a string.

Caveats

  • Rendered under another pattern, it throws an error of the form useParams("/a") rendered under "/b".
  • It works only under <Router>, not in pages under @k8ordo/framework.

useRoute

Import from @k8ordo/router

Returns the pattern that matched and its params, untyped.

ts
useRoute(): {
  pattern: string;
  params: Readonly<Record<string, string>>;
}

Returns

Pick<Match, 'pattern' | 'params'> — The matched pattern and its params.

Caveats

  • Outside <Router>, or where no page matched, it throws useRoute must render inside a matched <Router>.

normalizePathname

Import from @k8ordo/router

Normalizes a path by the router’s own rule. A trailing slash is dropped, and / alone is kept.

ts
normalizePathname(pathname: string): string

Parameters

pathnamestring
The path to normalize.

Caveats

  • Only the trailing slash is dropped. Repeated slashes inside the path and percent-encoding are left as they are.
ts
normalizePathname('/products/'); // '/products'
normalizePathname('/'); // '/'

withBase

Import from @k8ordo/router

Prepends Vite’s base to a path without it, as the route table writes paths.

ts
withBase(pathname: string, base?: string): string

Parameters

pathnamestring
A path without base.
basestring
Vite’s base. Left out, it is read from import.meta.env.BASE_URL. Pass it from code that Vite does not process.

Returns

string — The path with base prepended.

Caveats

  • A relative base such as ./ adds and removes nothing.

withoutBase

Import from @k8ordo/router

Removes Vite’s base from a URL’s path.

ts
withoutBase(pathname: string, base?: string): string | null

Parameters

pathnamestring
A URL’s path.
basestring
Vite’s base. Left out, it is read from import.meta.env.BASE_URL. Pass it from code that Vite does not process.

Returns

string | null — The path without base, or null for a path outside it.

Caveats

  • A relative base such as ./ adds and removes nothing.
ts
withBase('/products', '/docs/'); // '/docs/products'
withoutBase('/docs/products', '/docs/'); // '/products'
withoutBase('/elsewhere', '/docs/'); // null

notFound

Import from @k8ordo/router

Signals from a page under @k8ordo/framework that nothing exists at its path.

ts
notFound(): never

Caveats

  • It throws, so nothing after it runs.
  • Under @k8ordo/framework, the nearest not-found.tsx is served with a 404.
  • Under <Router>, it is an error like any other.

isNotFound

Import from @k8ordo/router

Checks whether a value is the error notFound() throws.

ts
isNotFound(value: unknown): boolean

Parameters

valueunknown
The value to check.

Caveats

  • It checks a Symbol.for symbol rather than instanceof, so it works even with two copies of this package loaded.

PathnameProvider

Import from @k8ordo/router

Supplies the path usePathname returns during a server render and hydration.

ts
<PathnameProvider pathname={string}>{children}</PathnameProvider>

Parameters

pathnamestring
The path this render is for.

Caveats

  • <Router> and the runtime of @k8ordo/framework provide it themselves. An app writes it only when it builds its own host on useInterceptedNavigation.

BrowserPathname

Import from @k8ordo/router

Signals that a server render has no path to supply. Below it, usePathname and useMatch wait for the browser with use(browser()).

ts
<BrowserPathname>{children}</BrowserPathname>

Caveats

  • The browser renders what is inside the nearest <Suspense>.
  • The runtime of @k8ordo/framework puts it around a fallback.tsx. An app never writes it.

Import from @k8ordo/router

A context that tells the route table’s error components that a new page is on screen.

ts
<NavigationGeneration value={number}>
  {children}
</NavigationGeneration>

Parameters

valuenumber
The generation that useInterceptedNavigation returns.

Caveats

  • <Router> and the runtime of @k8ordo/framework provide it themselves.

useInterceptedNavigation

Import from @k8ordo/router

The navigation part of <Router>, on its own. It loads and applies the navigations it decides to handle, and finishes each once the new page is on screen.

ts
useInterceptedNavigation<T>(
  handler: NavigationHandler<T>,
): { readonly generation: number }

Parameters

handlerNavigationHandler<T>
An object of functions that decide how navigations are handled. Its shape is NavigationHandler.

Returns

{ readonly generation: number } — A generation that changes each time a new page is put on screen.

Caveats

  • Render what apply set through useDeferredValue, in the same component.
  • handler is read when the event fires, so a new object on every render is fine.
src/article-host.tsx
'use client';

import {
  NavigationGeneration,
  PathnameProvider,
  useInterceptedNavigation,
} from '@k8ordo/router';
import { useDeferredValue, useState } from 'react';
import type { ReactNode } from 'react';

type Props = { initial: ReactNode; pathname: string };

export function ArticleHost({ initial, pathname }: Props) {
  const [latest, setLatest] = useState(initial);
  const { generation } = useInterceptedNavigation<ReactNode>({
    claim: (url) => url.pathname.startsWith('/articles/'),
    load: (url, signal) => loadArticle(url, signal),
    apply: setLatest,
  });
  const shown = useDeferredValue(latest);

  return (
    <PathnameProvider pathname={pathname}>
      <NavigationGeneration value={generation}>
        {shown}
      </NavigationGeneration>
    </PathnameProvider>
  );
}

Routes

Import from @k8ordo/router

The type of the route table defineRoutes returns.

ts
type Routes<R extends RoutesRecord = RoutesRecord> = {
  kind: 'routes';
  record: R;
  match: (pathname: string) => Match | null;
  matchAll: (pathname: string) => IteratorObject<Match, undefined>;
};

Fields

kind'routes'
Always 'routes'.
recordR
The table passed to defineRoutes.
match(pathname) => Match | null
Matches a path and returns the first Match that fits, or null.
matchAll(pathname) => IteratorObject<Match, undefined>
An iterator over every pattern that fits a path, in the order the table declares them. It matches only as far as the iteration goes.

RoutesRecord

Import from @k8ordo/router

The type of the table itself. Keys are patterns starting with /, and values are RouteNodes.

ts
type RoutesRecord = Record<`/${string}`, RouteNode>;

RouteNode

Import from @k8ordo/router

The type of a value in the table: a page component, or an object with children.

ts
type RouteNode =
  | RouteComponent
  | {
      layout?: RouteComponent;
      error?: ErrorComponent;
      loading?: ComponentType;
      children: RoutesRecord;
    };

Fields

layoutRouteComponent
The layout wrapping the pages below.
errorErrorComponent
The component rendered in place of the page below when that page throws.
loadingComponentType
The component shown while a page below suspends. It receives no props.
childrenRoutesRecord
The table of pages below. Its keys continue the parent’s pattern.

RouteComponent

Import from @k8ordo/router

The type of a page or layout. A component declaring any props fits.

ts
type RouteComponent = ComponentType<never>;

Caveats

  • <Router> passes no props, and @k8ordo/framework passes params and more. The same component fits either table.

Match

Import from @k8ordo/router

The type of the result match returns.

ts
type Match = {
  pattern: string;
  params: Readonly<Record<string, string>>;
  stack: readonly RouteComponent[];
};

Fields

patternstring
The matched pattern, exactly as written in the table.
paramsReadonly<Record<string, string>>
The decoded param values.
stackreadonly RouteComponent[]
The components to render, outermost layout first and the page last.

ErrorProps

Import from @k8ordo/router

The props the route table’s error component receives.

ts
type ErrorProps = {
  readonly error: unknown;
  readonly reset: () => void;
};

Fields

errorunknown
The value thrown by the page below.
reset() => void
Renders the page below again, in place.

ErrorComponent

Import from @k8ordo/router

The type of the component named by the route table’s error.

ts
type ErrorComponent = ComponentType<ErrorProps>;

Import from @k8ordo/router

The type of navigateTo’s options.

ts
type NavigateToOptions = {
  history?: 'push' | 'replace';
};

Fields

history'push' | 'replace'
'push' adds a new history entry, and 'replace' replaces the current one. The default is 'push'.

MatchOptions

Import from @k8ordo/router

The type of the options useMatch and matchPath take.

ts
type MatchOptions = {
  readonly inclusive?: boolean;
};

Fields

inclusiveboolean
Lets a /* pattern fit its own page too. It changes nothing for a pattern not ending in /*.

MatchablePattern

Import from @k8ordo/router

The type of the patterns useMatch and matchPath take: a pattern from the table, or a linkable pattern followed by /*.

ts
type MatchablePattern =
  | RegisteredPattern
  | `${RegisteredNavigablePattern}/*`;

BoundParams

Import from @k8ordo/router

The type of what the function given to bindParams returns: values with exactly one URL spelling, by param name.

ts
type BoundParams = Readonly<Record<string, ParamValue>>;

Import from @k8ordo/router

The type of the object bindParams returns.

ts
type BoundLinks<Bound extends BoundParams> = {
  readonly href: (pattern, params?) => string;
  readonly navigateTo: (
    pattern,
    params?,
    options?: NavigateToOptions,
  ) => NavigationResult;
};

Fields

href(pattern, params?) => string
An href that fills in the params from source.
navigateTo(pattern, params?, options?) => NavigationResult
A navigateTo that fills in the params from source.

Import from @k8ordo/router

The type of the object useInterceptedNavigation takes.

ts
type NavigationHandler<T> = {
  claim: (url: URL) => boolean;
  load: (url: URL, signal: AbortSignal) => T | Promise<T>;
  apply: (value: T) => void;
  refresh?: (url: URL) => boolean;
};

Fields

claim(url: URL) => boolean
Whether to handle this navigation, answered synchronously during the event.
load(url: URL, signal: AbortSignal) => T | Promise<T>
Produces what to render for the URL. signal aborts when the navigation is overtaken.
apply(value: T) => void
Applies what was loaded, as an ordinary update outside any transition.
refresh(url: URL) => boolean
Whether a navigation that keeps the path should still load. Left out, it never does.

Register

Import from @k8ordo/router

The interface a route table is registered on. Add routes with declare module, and patterns are checked against the table.

ts
declare module '@k8ordo/router' {
  interface Register {
    routes: typeof routes;
  }
}

Caveats

  • Register once, in the app.
  • Under @k8ordo/framework it is generated into .k8ordo/register.gen.ts.

RegisteredPattern

Import from @k8ordo/router

The pattern of every page in the registered table, /* patterns included. Before registering, any string starting with /.

ts
type RegisteredPattern = Register extends {
  routes: Routes<infer R>;
}
  ? PatternOf<R>
  : `/${string}`;

RegisteredNavigablePattern

Import from @k8ordo/router

The patterns in the registered table a link can point at, which excludes those with /*. Before registering, any string starting with /.

ts
type RegisteredNavigablePattern = Register extends {
  routes: Routes<infer R>;
}
  ? NavigablePatternOf<R>
  : `/${string}`;

RegisteredParams

Import from @k8ordo/router

The params a link to pattern P takes. A param a schema typed takes that type, and the others take a ParamValue or a string.

ts
type RegisteredParams<P extends string>

RegisteredPageParams

Import from @k8ordo/router

The params the page at pattern P receives. A param a schema ran on is that schema’s output, and the others are strings.

ts
type RegisteredPageParams<P extends string>

PageProps

Import from @k8ordo/router

The props a page under @k8ordo/framework receives. The type argument is the pattern the page’s directory stands for.

ts
type PageProps<P extends RegisteredPattern> = {
  readonly params: RegisteredPageParams<P>;
  readonly pathname: string;
} & RequestProps &
  SearchProps<P>;

Fields

paramsRegisteredPageParams<P>
The params, typed by the schemas.
pathnamestring
The path this render is for.
requestRequest
The request. Only in server mode.
searchunknown
The value a page that exports search read. Only on such a page.

LayoutProps

Import from @k8ordo/router

The props a layout under @k8ordo/framework receives. The type argument must be a pattern the table has a page at.

ts
type LayoutProps<P extends RegisteredPattern> = {
  readonly params: ParamsOf<P>;
  readonly pathname: string;
  readonly children: ReactNode;
} & RequestProps;

Fields

paramsParamsOf<P>
The params, typed as strings even when a schema is declared.
pathnamestring
The path this render is for.
childrenReactNode
The page the layout wraps.
requestRequest
The request. Only in server mode.

RouteContext

Import from @k8ordo/router

The type of the argument a function exported from a route.ts under @k8ordo/framework receives.

ts
type RouteContext<P extends RegisteredPattern> = {
  readonly request: Request;
  readonly params: RegisteredPageParams<P>;
};

Fields

requestRequest
The incoming request.
paramsRegisteredPageParams<P>
The params, typed by the schemas as a page’s are.

PatternOf

Import from @k8ordo/router

Every page pattern in table R, exactly as written, /* patterns included.

ts
type PatternOf<R extends RoutesRecord>

Import from @k8ordo/router

The patterns in table R a link can point at, which excludes those with /*.

ts
type NavigablePatternOf<R extends RoutesRecord>

Import from @k8ordo/router

Compares Path segment by segment with the table’s linkable patterns. It is Path when one fits, and never when none does.

ts
type NavigablePath<D, Path extends string>

Caveats

  • Where a pattern has a :param, any one non-empty segment fits.
  • A path with a trailing slash is never.
ts
type A = NavigablePath<typeof routes, '/products/42'>;
// '/products/42'
type B = NavigablePath<typeof routes, '/products/42/reviews'>;
// never

ParamsOf

Import from @k8ordo/router

The params derived from a pattern string. Every value is a string.

ts
type ParamsOf<Pattern extends string>
ts
type Params = ParamsOf<'/:locale/products/:id'>;
// { locale: string; id: string }

PathFor

Import from @k8ordo/router

The type of a path that fits the pattern, with any string where each :param is.

ts
type PathFor<Pattern extends string>
ts
type Path = PathFor<'/:locale/products/:id'>;
// `/${string}/products/${string}`

ParamValue

Import from @k8ordo/router

The values with exactly one URL spelling. A link’s params take them.

ts
type ParamValue = string | number | bigint | boolean;

StandardSchemaLike

Import from @k8ordo/router

The Standard Schema shape. A schema from any library implementing it fits, zod and zod/mini included.

ts
type StandardSchemaLike<Output = unknown> = {
  readonly '~standard': {
    readonly types?: { readonly output: Output } | undefined;
  };
};

Caveats

  • The schema types are mostly used by generated code. For the types an app writes by hand, PageProps and LayoutProps are enough.

SchemaOutput

Import from @k8ordo/router

The type of the value a schema produces.

ts
type SchemaOutput<Schema> =
  Schema extends StandardSchemaLike<infer Output> ? Output : never;

ParamsSchemaFor

Import from @k8ordo/router

A schema that can be pattern P’s paramsSchema. Its output’s keys are some of the pattern’s params.

ts
type ParamsSchemaFor<Pattern extends string> = StandardSchemaLike<
  Partial<Record<keyof ParamsOf<Pattern> & string, unknown>>
>;

ParsedParams

Import from @k8ordo/router

A pattern’s params with the output of a list of schemas applied on top. The list runs outermost layout first and the page last. A param no schema covers stays a string.

ts
type ParsedParams<
  Pattern extends string,
  Schemas extends readonly unknown[],
>

ParsedParamsMap

Import from @k8ordo/router

Turns each pattern’s list of schemas into its ParsedParams. The generated Register’s params is one.

ts
type ParsedParamsMap<
  Schemas extends Record<string, readonly unknown[]>,
>
k8ordo

React libraries that use Baseline features without holding back.