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.
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 aTypeError. The message reads likeroute pattern "/x" is declared twice. - Patterns are tried in the order written, and the first that fits wins. Put
/*last.
routes.tsexport 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.
<Router routes={Routes} />Parameters
routesRoutes- The route table
defineRoutesreturned.
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.
<Outlet />Caveats
- Rendered outside
<Router>, it throwsOutlet must render inside <Router>. Under@k8ordo/framework, a layout renderschildreninstead.
href
Import from @k8ordo/router
Builds the URL a link points at from a pattern and its params.
href<P extends RegisteredNavigablePattern>(
pattern: P,
params?: RegisteredParams<P>,
): stringParameters
patternP- The pattern to link to. With
Registeraugmented, 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 aTypeErrorcontainingis a wildcard. A param without a value throws one containingneeds a value for, and a value that cannot be spelled in a URL one containinghas no URL spelling.
href('/products'); // '/products'
href('/products/:id', { id: 42 }); // '/products/42'navigateTo
Import from @k8ordo/router
Builds a URL from a pattern and its params, and navigates there.
navigateTo<P extends RegisteredNavigablePattern>(
pattern: P,
params?: RegisteredParams<P>,
options?: NavigateToOptions,
): NavigationResultParameters
patternP- The pattern to link to. With
Registeraugmented, 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,
finishedrejects with anAbortError.
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.
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
hrefornavigateTo.
Returns
BoundLinks<Bound> — An href and a navigateTo that fill in what source returns.
Caveats
- A param
sourcesupplies may be left out. Passing it overrides the value. - When the pattern names a param, the options are always the third argument. When
sourcesupplies every param, passundefinedas the second.
usePathname
Import from @k8ordo/router
Returns the path the browser is on.
usePathname(): stringReturns
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/frameworkrenders. During hydration, it also works under<Router>. Elsewhere it throws an error starting withusePathname 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.
useMatch<P extends MatchablePattern>(
pattern: P,
options?: MatchOptions,
): ParamsOf<P> | nullParameters
patternP- A pattern from the table, or one followed by
/*./*fits the paths below that pattern. optionsMatchOptions- With
inclusiveset totrue, 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.
matchPath<P extends MatchablePattern>(
pattern: P,
pathname: string,
options?: MatchOptions,
): ParamsOf<P> | nullParameters
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
inclusiveset totrue, a/*pattern also fits its own page.
Returns
ParamsOf<P> | null — The params when it fits, or null.
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.
usePendingPathname(): string | nullReturns
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
nullonce 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
nullin a server render.
useParams
Import from @k8ordo/router
Reads a page’s params, typed by its pattern.
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.
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 throwsuseRoute 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.
normalizePathname(pathname: string): stringParameters
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.
normalizePathname('/products/'); // '/products'
normalizePathname('/'); // '/'withBase
Import from @k8ordo/router
Prepends Vite’s base to a path without it, as the route table writes paths.
withBase(pathname: string, base?: string): stringParameters
pathnamestring- A path without
base. basestring- Vite’s
base. Left out, it is read fromimport.meta.env.BASE_URL. Pass it from code that Vite does not process.
Returns
string — The path with base prepended.
Caveats
- A relative
basesuch as./adds and removes nothing.
withoutBase
Import from @k8ordo/router
Removes Vite’s base from a URL’s path.
withoutBase(pathname: string, base?: string): string | nullParameters
pathnamestring- A URL’s path.
basestring- Vite’s
base. Left out, it is read fromimport.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
basesuch as./adds and removes nothing.
withBase('/products', '/docs/'); // '/docs/products'
withoutBase('/docs/products', '/docs/'); // '/products'
withoutBase('/elsewhere', '/docs/'); // nullnotFound
Import from @k8ordo/router
Signals from a page under @k8ordo/framework that nothing exists at its path.
notFound(): neverCaveats
- It throws, so nothing after it runs.
- Under
@k8ordo/framework, the nearestnot-found.tsxis 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.
isNotFound(value: unknown): booleanParameters
valueunknown- The value to check.
Caveats
- It checks a
Symbol.forsymbol rather thaninstanceof, 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.
<PathnameProvider pathname={string}>{children}</PathnameProvider>Parameters
pathnamestring- The path this render is for.
Caveats
<Router>and the runtime of@k8ordo/frameworkprovide it themselves. An app writes it only when it builds its own host onuseInterceptedNavigation.
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()).
<BrowserPathname>{children}</BrowserPathname>Caveats
- The browser renders what is inside the nearest
<Suspense>. - The runtime of
@k8ordo/frameworkputs it around afallback.tsx. An app never writes it.
NavigationGeneration
Import from @k8ordo/router
A context that tells the route table’s error components that a new page is on screen.
<NavigationGeneration value={number}>
{children}
</NavigationGeneration>Parameters
valuenumber- The
generationthatuseInterceptedNavigationreturns.
Caveats
<Router>and the runtime of@k8ordo/frameworkprovide 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.
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
applyset throughuseDeferredValue, in the same component. handleris 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.
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
Matchthat fits, ornull. 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.
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.
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.
type RouteComponent = ComponentType<never>;Caveats
<Router>passes no props, and@k8ordo/frameworkpassesparamsand more. The same component fits either table.
Match
Import from @k8ordo/router
The type of the result match returns.
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.
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.
type ErrorComponent = ComponentType<ErrorProps>;NavigateToOptions
Import from @k8ordo/router
The type of navigateTo’s options.
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.
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 /*.
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.
type BoundParams = Readonly<Record<string, ParamValue>>;BoundLinks
Import from @k8ordo/router
The type of the object bindParams returns.
type BoundLinks<Bound extends BoundParams> = {
readonly href: (pattern, params?) => string;
readonly navigateTo: (
pattern,
params?,
options?: NavigateToOptions,
) => NavigationResult;
};Fields
href(pattern, params?) => string- An
hrefthat fills in the params fromsource. navigateTo(pattern, params?, options?) => NavigationResult- A
navigateTothat fills in the params fromsource.
NavigationHandler
Import from @k8ordo/router
The type of the object useInterceptedNavigation takes.
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.
signalaborts 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.
declare module '@k8ordo/router' {
interface Register {
routes: typeof routes;
}
}Caveats
- Register once, in the app.
- Under
@k8ordo/frameworkit 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 /.
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 /.
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.
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.
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.
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
searchread. 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.
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.
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.
type PatternOf<R extends RoutesRecord>NavigablePatternOf
Import from @k8ordo/router
The patterns in table R a link can point at, which excludes those with /*.
type NavigablePatternOf<R extends RoutesRecord>NavigablePath
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.
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.
type A = NavigablePath<typeof routes, '/products/42'>;
// '/products/42'
type B = NavigablePath<typeof routes, '/products/42/reviews'>;
// neverParamsOf
Import from @k8ordo/router
The params derived from a pattern string. Every value is a string.
type ParamsOf<Pattern extends string>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.
type PathFor<Pattern extends string>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.
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.
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,
PagePropsandLayoutPropsare enough.
SchemaOutput
Import from @k8ordo/router
The type of the value a schema produces.
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.
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.
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.
type ParsedParamsMap<
Schemas extends Record<string, readonly unknown[]>,
>