Routing

The directories under src/routes/ are the application’s URLs. Once you know the rules for directories and files, a page, a redirect or a feed is one file in the right place.

On this page

Directories and URLs

text
src/routes/
  layout.tsx
  page.tsx
  not-found.tsx
  products/
    page.tsx
    [id]/
      page.tsx
  (docs)/
    layout.tsx
    guide/
      page.tsx
  • page.tsx: the page at /.
  • products/page.tsx: the page at /products.
  • products/[id]/page.tsx: the page at /products/:id. Open /products/42, and the page receives 42 as params.id.
  • (docs)/guide/page.tsx: the page at /guide.

Directory name shapes

The shape of a directory name decides what it adds to the URL.

  • products: adds one segment, exactly as written. Letters, digits, ., _, ~ and - are allowed.
  • [id]: a parameter that takes one segment. Its name starts with a letter or _.
  • [...path]: a parameter that takes every remaining segment. Server mode only.
  • (docs): a group, which adds no segment. Use it to give part of routes/ a layout or an error.tsx of its own.
  • A name starting with .: never read, directory or file. A .DS_Store or an editor’s temporary file does not break the build.

[...name] directories

src/routes/files/[...path]/page.tsx
import type { PageProps } from '@k8ordo/framework';

export default function FilePage({ params }: PageProps<'/files/:path+'>) {
  return <h1>{params.path.join(' / ')}</h1>;
}

A [...path] directory takes every segment from its position on. The value is an array of segments: at /files/a/b, params.path is ['a', 'b']. Its pattern is written /files/:path+.

Each segment is decoded on its own, so /files/a%2Fb/c is ['a/b', 'c']. A layout.tsx, route.ts and guard.ts in the same directory receive the same array.

It takes one segment or more. It does not answer /files, so the page for /files goes in files/page.tsx. There is no form that also answers with no segment, such as [[...path]].

No directory goes below [...path], a group included, and one level holds one [...name]. It cannot hold not-found.tsx, fallback.tsx or paths.ts either.

ts
import { href } from '@k8ordo/framework';

href('/files/:path+', { path: ['a/b', 'c'] }); // '/files/a%2Fb/c'

href takes the array of segments, escapes each one and joins them with /. An empty array or an empty segment throws a TypeError.

A params reads the array with field.list(). See Parameters.

Warning

Pitfall

A static mode build fails on a [...name] directory, naming it. The number of segments differs per request, so the build cannot decide which paths to write. The error ends with the line this application wants mode: 'server'.

Route files

A directory may hold only files with these nine names, extension included. Even a page.ts, with only the extension wrong, fails the build.

  • page.tsx: the page shown at the directory’s URL.
  • layout.tsx: wraps whatever renders below it, received as children.
  • not-found.tsx: shown for any URL below it that no route matched.
  • error.tsx: rendered in place of what is below it when that throws.
  • loading.tsx: rendered while the page below it loads.
  • redirect.ts: default-exports a destination, instead of a page.
  • route.ts: returns a Response instead of a page.
  • guard.ts: runs before any request below it is handled, and stops it or lets it through. Server mode only.
  • paths.ts: returns the values of its directory’s parameter. It sits in a parameter’s directory, such as [id], and a static mode build reads it.
  • fallback.tsx: answers a URL whose value no paths.ts returned, in place of the page.tsx beside it. Static mode only.

src/routes/ holds route files and directories, nothing else. Components go in src/components/, and every other module — Server Actions, form and state definitions, data, helpers — in src/lib/.

Page and layout props

src/routes/products/[id]/page.tsx
import type { PageProps } from '@k8ordo/framework';

export default function ProductPage({
  params,
  pathname,
}: PageProps<'/products/:id'>) {
  return (
    <>
      <h1>{params.id}</h1>
      <p>{pathname}</p>
    </>
  );
}

A page receives params, and a layout receives children. Both receive pathname, the URL being rendered. A layout above a parameter reads the value from pathname.

PageProps and LayoutProps from @k8ordo/framework are these props looked up by pattern. They read the generated route table, so the pattern string is the only type argument. PageProps takes only a pattern that has a page, while LayoutProps takes the pattern of the layout for /products even without products/page.tsx.

Under server mode a page and a layout also receive request. Reading its headers and cookies is covered in Request and cookies.

Router API

src/components/products-link.tsx
'use client';

import { href, useMatch } from '@k8ordo/framework';

export function ProductsLink() {
  const onProducts = useMatch('/products') !== null;
  const inProducts = useMatch('/products/*', { inclusive: true }) !== null;
  return (
    <a
      aria-current={onProducts ? 'page' : inProducts ? 'true' : undefined}
      href={href('/products')}
    >
      Products
    </a>
  );
}

The APIs for links and the current URL, such as href and useMatch, are imported from @k8ordo/framework, which re-exports them from @k8ordo/router by name. The hooks work only in Client Components.

useParams is not in @k8ordo/framework: the browser holds no route table, so it would have no route to read. What to use instead is covered in Server and browser.

The locale segment

src/routes/[locale]/layout.tsx
import type { LayoutProps } from '@k8ordo/framework';

import { locales } from '../../i18n';

export const { params } = locales;

export default function LocaleLayout({
  children,
}: LayoutProps<'/:locale'>) {
  return children;
}

From the [locale] layout, export the params of the locales you defined with defineLocales. The declaration accepts only the locales in the set. Where the accepted locale is read is covered in Current locale.

The framework reads the parameter with this declaration as it does any params, and renders the pages below in the locale it accepted. / has no locale, so the application itself picks a language at / and redirects to a URL that has one. Picking it is covered in Negotiation.

Under static mode a page is written per locale, so [locale]/paths.ts returns locales.all. Writing it is covered in Parameters.

/ under server mode

text
src/routes/
  layout.tsx
  (home)/
    guard.ts
    page.tsx
  [locale]/
    layout.tsx
    page.tsx
src/routes/(home)/guard.ts
import { href } from '@k8ordo/framework';
import { cookies, redirect } from '@k8ordo/framework/server';
import type { Guard } from '@k8ordo/framework/server';

import { locales } from '../../i18n';

const guard: Guard<'/'> = ({ request }) => {
  const locale = locales.negotiateRequest(request, {
The cookie first, then Accept-Language
    chosen: cookies().get('locale'),
  });
  redirect(href('/:locale', { locale }));
A guard’s `redirect()` answers 303; `href()` adds Vite’s `base`
};

export default guard;
src/routes/(home)/page.tsx
export default function HomePage() {
  return null;
}

Server mode only. Requests for / are answered by (home)/guard.ts before any page renders. It hands the earlier choice, read with cookies().get('locale'), to negotiateRequest as chosen to pick a locale, and sends the visitor to that locale’s URL with redirect(href('/:locale', { locale })). A redirect is redirect(), not a Response built by hand, and its URL comes from href(), as a link’s does.

Put the guard and the page in a group such as (home)/. A guard.ts directly in src/routes/ would redirect requests for /en/… as well. The page.tsx never renders, but it cannot be left out: the build refuses a (home)/ with no page.

A visitor without JavaScript is redirected all the same. A client navigation to / ends at the locale’s URL too, since the guard answers its payload request as well.

/ under static mode

src/routes/page.tsx
'use client';

import { href } from '@k8ordo/framework';
import { useEffect } from 'react';

import { locales } from '../i18n';

export default function HomePage() {
  useEffect(() => {
    navigation.navigate(
      href('/:locale', {
        locale: locales.negotiate(navigator.languages),
      }),
      { history: 'replace' },
    );
  }, []);

  return null;
}

Static mode refuses a guard.ts, so the / page moves the visitor in the browser: it picks a locale from navigator.languages and goes to that locale’s URL with navigation.navigate(href(…)). The page itself renders nothing.

The move happens in a useEffect: the build renders this page outside a browser too, where there is neither a Navigation API nor a visitor’s navigator.languages. With history: 'replace', the back button never returns to / only to be sent on again.

Information

Note

A visitor without JavaScript stays on /.

src/routes/page.tsx
useEffect(() => {
  void cookieStore.get('locale').then((saved) => {
    navigation.navigate(
      href('/:locale', {
        locale: locales.negotiate([
          saved?.value,
          ...navigator.languages,
        ]),
      }),
      { history: 'replace' },
    );
  });
}, []);

When the locale chosen in a language switcher is saved in a cookie, put its value in front of navigator.languages and pass both to negotiate. That is the order negotiateRequest reads them in under server mode. Without the cookie the value is undefined, which negotiate skips.

<html lang> and dir

src/routes/layout.tsx
import type { LayoutProps } from '@k8ordo/framework';

import { locales } from '../i18n';

export default function RootLayout({ children }: LayoutProps<'/'>) {
  const locale = locales.getLocale();

  return (
    <html dir={locales.definitions[locale].dir} lang={locale}>
      <body>{children}</body>
    </html>
  );
}

The root layout sits above [locale], but locales.getLocale() reads the current locale there, because rendering starts after the declarations have read the params. Write it into lang and dir on <html>.

Outside [locale], it returns the default locale. On a 404, it returns the locale the declarations of the layouts above not-found.tsx accepted. Either way, it is the locale the page’s messages use.

Route order

text
src/routes/
  about/
    page.tsx
  (shop)/
    sale/
      page.tsx
    [id]/
      page.tsx

Directories have no order of their own, so the generated route table picks one. At each level a fixed segment is tried first, then a parameter, then a [...name], and not-found.tsx comes last. Put [id]/ directly beside about/, and /about still reaches about/.

A group, though, keeps its routes together in one place. The table does not reorder across groups. In the example above, (shop) holds the fixed segment sale/, so it ranks level with about/. At the same rank routes sort by name, which puts (shop) first.

So (shop)/[id]/ answers /about first, and about/page.tsx never renders. This shape fails the build with an error that begins "/about" can never match.

Invalid structure

When a file or directory breaks the rules, the build fails. The error begins routes/ is not a valid pathname space: and lists one line per problem. It lists every problem it found, not just the first, and each line names the file.

  • A file that is not a route file (products/helper.ts)
  • A malformed directory name ([123], (docs, pro ducts)
  • A parameter named the same as one above it ([id]/things/[id]/)
  • A directory below a [...name] (files/[...path]/raw/)
  • Two [...name] directories at one level (files/[...a]/ and files/[...b]/)
  • A directory with no page, redirect.ts or route.ts anywhere below it (only a layout or an error.tsx, say)
  • Pages at the same URL in different groups ((a)/page.tsx and (b)/page.tsx)
  • Any two of page.tsx, redirect.ts and route.ts in one directory
  • A route.ts that exports no method
  • A page that never shows because a route inside a group answers first
  • A fallback.tsx with no page.tsx beside it
  • A fallback.tsx in the same directory as a layout.tsx
  • A fallback.tsx for a page with no parameter
  • A fallback.tsx for a page whose every parameter a layout above receives

vite dev refuses to start with the same error when a problem exists at startup. A problem introduced while it runs is logged as routes/<path>: <message>, and the server keeps going. While a problem remains, .k8ordo/ is not rewritten.

Under static mode the build also fails on what needs a server. Which ones, and why, is covered in Choosing a mode.

Loading state

src/routes/products/loading.tsx
export default function ProductsLoading() {
  return <p>Loading products…</p>;
}

A loading.tsx beside a layout.tsx or a page.tsx is rendered while the page below it loads. It receives no props.

Under static mode a page is written whole into a file, so its HTML never shows a loading.tsx. A client navigation rarely shows one either: the payload is a file too, and usually arrives in one piece.

Under server mode a document waits for the page’s own component before it is sent, so its HTML does not show it, and a visitor without JavaScript, or a crawler, sees the page. The exception is a component inside the page that awaits data outside a <Suspense> of its own: the HTML then shows it in the page’s place. During a client navigation it shows from when the payload starts arriving until the server has finished rendering the page.

src/components/progress.tsx
'use client';

import { usePendingPathname } from '@k8ordo/framework';

export function Progress() {
  const pending = usePendingPathname();
  if (pending === null) return null;
  return <p role="status">Loading {pending}…</p>;
}

Moving to another page within a directory already on screen keeps the current page showing until the next one arrives. To show something meanwhile, read where the navigation is going with usePendingPathname().

route.ts

src/routes/feed.xml/route.ts
import type { RouteContext } from '@k8ordo/framework';

import { renderFeed } from '../../lib/feed.server';

export async function GET({ request }: RouteContext<'/feed.xml'>) {
  const { origin } = new URL(request.url);
  return new Response(await renderFeed(origin), {
    headers: { 'content-type': 'application/rss+xml' },
  });
}

A URL that returns something other than a page, such as an RSS feed or JSON, gets a route.ts. It exports a function named after each HTTP method it handles, and that function returns a Response. The function receives { request, params }, typed RouteContext. Its params are typed by the declarations, as a page’s are.

A directory named like a file, such as feed.xml, is an ordinary segment, so feed.xml/route.ts is the URL /feed.xml. The Response a route.ts returns gets none of the layouts above it. A client navigation to its URL reloads the whole page.

Static mode

The build calls GET once per URL and writes the Response it returns as the file at that URL: feed.xml/route.ts becomes dist/client/feed.xml. A route.ts with parameters is written once per value the paths.ts files above it return, as a page is. The origin of request.url is the site given to framework().

Warning

Pitfall

These route.ts files cannot become files, so they fail the build:

  • A route.ts exporting a method other than GET (vite dev refuses it too)
  • A route.ts whose GET returns anything but 200
  • A route.ts at /
  • A route.ts with pages below it
  • A route.ts writing a file the build writes itself (404.html beside a not-found.tsx, _redirects when there are shells, client-files.json, a page’s index.html and index.rsc). The error names the route.ts and the other side; remove one of them. vite dev does not stop

A written file keeps no type, so a static host picks one from its extension. So do vite preview and serve, which send a file without one as application/octet-stream. On Vercel, vercel() serves it with the Content-Type its GET returned — the type vite dev sends.

Warning

Pitfall

A Response given a string body gets text/plain;charset=UTF-8 when no type is written, so a sitemap.xml returned that way is sent as plain text on Vercel and in vite dev. Write the type in a route.ts.

Server mode

Any of the seven HTTP methods may be exported. A method it does not export gets a 405, with the exported ones listed in Allow. Without a HEAD export, the GET response is returned without its body.

The guard.ts files above it run first. cookies(), responseHeaders() and requestHeaders() from @k8ordo/framework/server work inside a route.ts too.

Warning

Pitfall

A POST to a route.ts is not checked for the same origin, unlike a Server Action: what posts there, such as a webhook, comes from elsewhere. Write the checks you need inside the route.ts.

The generated .k8ordo/

.k8ordo/routes.gen.ts
import { defineRoutes } from '@k8ordo/framework/generated';
// …
const page = () => import('../src/routes/page');
// …

export const routes = defineRoutes({
  '/': {
    layout: layout satisfies Layout<'/'>,
    children: {
      '/': lazy(page) satisfies Page<'/'>,
      '/products': {
        children: {
          '/': lazy(products_page) satisfies Page<'/products'>,
          '/:id': lazy(products_id_page) satisfies Page<'/products/:id'>,
        },
      },
    },
  },
});

The framework writes a route table and its types, made from routes/, into .k8ordo/. It writes when vite dev starts, when vite build begins and when k8ordo generate runs, and during development whenever a file under routes/ or src/i18n.ts changes.

  • routes.gen.ts: the route table itself. It checks each route file against its directory’s pattern with satisfies. page.tsx, not-found.tsx, route.ts and fallback.tsx are read with import() when a request reaches them, and a page or a not-found.tsx stands in the table as lazy().
  • register.gen.ts: registers the table with the framework, which types the patterns href() and useMatch() take. Under server mode it also adds request to PageProps and LayoutProps. When the application depends on @k8ordo/i18n and src/i18n.ts exports locales, it writes @k8ordo/i18n’s Register too.
  • .gitignore: ignores everything in it with *. That keeps .k8ordo/ out of git, so nothing goes into the application’s own .gitignore.

It is generated, so do not edit it. It is plain TypeScript importing from @k8ordo/framework/generated, and reading it shows what is checked.

vite build does not type-check, so run tsc to see the satisfies checks. In a fresh clone or in CI, run k8ordo generate before tsc. It reads the Vite config in the application’s directory as vite build does, writes .k8ordo/, and builds nothing. It reads no paths.ts and touches no data a page reads, so it runs in a CI job with no database or secrets. When routes/ has a problem the build lists under routes/ is not a valid pathname space:, it fails with the same error and writes nothing. What a static mode build refuses on top of that — a guard.ts, a route.ts answering more than GET, a page reading search, an export *, a Server Action, whatever a paths.ts returns — it does not check, so its success does not mean the build will succeed.

.github/workflows/ci.yml
- run: pnpm exec k8ordo generate
- run: pnpm exec tsc --noEmit

Titles and metadata

src/routes/products/[id]/page.tsx
import type { PageProps } from '@k8ordo/framework';

export default function ProductPage({
  params,
}: PageProps<'/products/:id'>) {
  return (
    <>
      <title>{`Product ${params.id}`}</title>
      <meta content="One product" name="description" />
      <h1>{params.id}</h1>
    </>
  );
}

There is no metadata API. React 19 moves a <title>, <meta> or <link> rendered in any component into <head>. A page renders its title where it renders everything else.

Keep one <title> on screen at a time. The root layout renders none, and each page and not-found.tsx renders its own. Render two and both are output; the later one does not replace the earlier.

Counting page views

src/components/page-views.tsx
'use client';

import { usePageView } from '@k8ordo/framework';

export function PageViews() {
  usePageView(({ url }) => {
    gtag('event', 'page_view', {
      page_location: url.href,
      page_title: document.title,
    });
  });
  return null;
}

Rendered from the root layout, this calls the callback of usePageView for every page the visitor is shown: the document’s load, each page change with going back and forward included, and the back/forward cache bringing the document back. A change of only the query or the fragment does not call it, nor does a page that exports search rendered again for a new query.

A page change is not a document load, and it is not pushState either. The router changes pages through the Navigation API, so a tool that counts only loads, or that watches the History API, misses it. Turn off the tool’s own counting of history changes, or page changes are counted twice.

src/components/view-counter.tsx
'use client';

import { href, usePageView } from '@k8ordo/framework';

export function ViewCounter({ slug }: { slug: string }) {
  usePageView(() => {
    void fetch(href('/api/posts/:slug/views', { slug }), {
      method: 'POST',
      keepalive: true,
    });
  });
  return null;
}

A count that belongs to one page is rendered from that page, where its params are at hand. When the callback runs and what it receives are in the router’s Location page.

MDX

vite.config.ts
import { framework } from '@k8ordo/framework/vite';
import mdx from '@mdx-js/rollup';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    { enforce: 'pre', ...mdx() },
    framework({ mode: 'static', site: 'https://example.com' }),
  ],
});

The framework compiles no MDX. Add a compiler such as @mdx-js/rollup as a Vite plugin ahead of framework(), with enforce: 'pre' so it runs before the framework's transforms.

src/routes/posts/[slug]/page.tsx
import { notFound } from '@k8ordo/framework';
import type { PageProps } from '@k8ordo/framework';
import type { ComponentType } from 'react';

const posts = import.meta.glob<{ default: ComponentType }>(
  '../../../content/*.mdx',
);

export default async function PostPage({ params }: PageProps<'/posts/:slug'>) {
  const load = posts[`../../../content/${params.slug}.mdx`];
  if (load === undefined) notFound();
  const { default: Post } = await load();
  return <Post />;
}

An .mdx file is a module whose default export is a Server Component. A page imports it statically, or reads it late through import.meta.glob, so each page reads only its own article.

src/content/hello.mdx
import './post.module.css';

# Hello

The stylesheet above is linked on this post's page.

CSS an .mdx file imports is linked in the HTML of the pages that render the file and of no other, as a .tsx module’s is. The import needs no query.

The CSS rides on the components a module exports. A module that imports CSS and exports only a table of components (components) carries none of it to a page that another module renders with the table. Export a component that renders with the table from the module that imports the CSS.

Prefetching links

tsx
<nav data-k8ordo-prefetch="false">
  <a href={href('/reports')}>Reports</a>
  <a data-k8ordo-prefetch="true" href={href('/')}>
    Home
  </a>
</nav>

When a pointer moves onto a link, the client runtime fetches the payload of the page it points to. Focusing the link or starting a press on it does the same. There is nothing to set up: every <a> on the page counts, including the ones a component library renders. These links are not prefetched:

  • one to another origin, or outside Vite’s base
  • one with download, or with a target other than _self
  • one to the page on screen

Under static mode, where the primary pointer is coarse ((pointer: coarse)), the links on screen are prefetched too. Once the document’s load event has fired, each link that has stayed on screen for a second is fetched, one at a time in the order they came into view, at low priority. A link that leaves the screen before its turn is passed over. While a page change loads, nothing more is fetched, and a prefetch on its way to another page is cancelled. That link is fetched first once the next page shows.

To stop prefetching, mark the link or any element around it data-k8ordo-prefetch="false". Use it for links to pages that are expensive to render, or for a long list a visitor scrolls through on a phone. The nearest element carrying the attribute decides, so "true" brings one link back inside a region that opted out.

Under server mode the links on screen are not prefetched: every link a visitor scrolls past would be a render on the server. A prefetched page is used once, by the next navigation to it, and only within 30 seconds of the fetch starting. After that the navigation fetches it again. A Server Action’s result drops everything prefetched too.

Under static mode a page is a file that stays the same until the next deploy, so the pages fetched are kept. A page prefetched, one a navigation fetched, and the page first opened are each used by every navigation to them, going back and forward included, without asking the host again. The tab keeps the 50 pages it used most recently. A page left while it was still arriving goes on arriving, so going back to it shows it whole. Under vite dev pages are rendered per request in either mode, and are kept as under server mode.

A static build also writes client-files.json: for each page, the scripts and stylesheets its Client Components load and the stylesheets its Server Components load, less those every page loads. The runtime reads it once, at low priority, after the document starts. Whenever it asks for a page’s payload, it starts fetching that page’s files at the same moment and at the same priority — scripts with <link rel="modulepreload">, stylesheets with <link rel="preload" as="style"> — instead of waiting a round trip for the payload to name them. The links on screen are prefetched only once the list has been read. A stylesheet still applies only once the page that uses it is shown, and the page waits for it to arrive. A page the list leaves out, such as a value a shell answers, loads as it would without the list.

Information

Note

Neither the browser’s Speculation Rules nor the Network Information API, which would say whether a visitor saves data, is used: neither is Baseline.

Playground

Prefetch demo

This site runs on @k8ordo/framework in static mode, so pointing at a link really fetches its index.rsc and shows it in the list below.

Payloads fetched

None yet

Try it

  1. Point at “The parameters page”. Its index.rsc joins the list.
  2. “The deploy page” sits inside data-k8ordo-prefetch="false", so pointing at it adds nothing.
  3. Point at “The parameters page” again. Nothing is added: this site runs in static mode, so a page fetched once is kept.
  4. Open this page on a touch screen. The links join the list as they come into view, with nothing pointed at.
  5. Point at a link to another page in the header or the sidebar. It joins the list the same way.
k8ordo

React libraries that use Baseline features without holding back.