Parameters

A page under a directory such as [id] receives part of its URL as a parameter. A declaration built with field types the value. Under static mode a paths.ts returns the values to write, and under server mode search declares the query.

On this page

Parameters as strings

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

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

A page under an [id] directory receives that URL segment as params.id. A URL holds only strings, so without a declaration the value is a string.

Typing with a declaration

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

export const params = field.object({
The export is named params, after the prop it types
  id: field.integer({ min: 1 }),
});

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

Export params from page.tsx, and the declaration reads the parameter before the page renders. field.integer() reads the segment as a number, so params.id in PageProps<'/products/:id'> is a number. The type comes from the generated route table, so you never write the type of params by hand.

A page takes its params one level down, as { params: { id } }. Taken as { params }, the binding would shadow the exported params, which the no-shadow lint rule refuses.

params takes field.object({ … }), with a kind per parameter. The kinds, such as string, integer and enum, each read the segment by the rules of the HTML input of that type. Exporting anything but field.object() fails with an error that begins params: a route file exports … as params.

Import field from @k8ordo/field. locales.params from @k8ordo/i18n is a declaration of the same kind. The export is found by parsing the file, so a destructured export const { params } = locales hands over a declaration made elsewhere.

Warning

Pitfall

A declaration is data, so it cannot transform what it reads: a segment never comes out uppercased, or as a Date. Nor can it hold a check written as a function, or an asynchronous one. Make such a check in the page, and call notFound() when it fails.

Export params from a file without 'use client'. A value exported from a 'use client' module reaches the server as a client reference, which cannot be read as a declaration.

Layout declarations

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;
}
src/routes/[locale]/products/[id]/page.tsx
import { field } from '@k8ordo/field';
import type { PageProps } from '@k8ordo/framework';

export const params = field.object({
  id: field.integer({ min: 1 }),
});

export default function ProductPage({
  params: { locale, id },
}: PageProps<'/:locale/products/:id'>) {
  return <h1 lang={locale}>{id.toFixed(0)}</h1>;
}

A layout.tsx can export params too. Before the page renders, the declarations read the params from the outermost layout down, and the page’s own reads last.

Each declaration reads the strings the URL carried, never what an earlier one read. When two declare the same parameter, the later one’s value is the one kept. A parameter no declaration names stays a string.

Here the [locale] layout reads the locale and the page reads id, and the page receives both in params. A path segment is never empty, so a declared parameter is never undefined, required or not.

Values a declaration refuses

When a declaration refuses a value, the route is treated as if it had not matched the URL. /products/shoes never becomes a page holding NaN. The next candidate in the route table is tried, and in the end not-found.tsx is rendered with a 404.

Under static mode that 404 is a single file, 404.html. Under server mode the response is a 404 status with not-found.tsx as its body, both for a document load and for a client navigation’s payload request.

A not-found.tsx rejects nothing. The params.locale that the one at /:locale/* receives can be a string such as fr that names no locale. Check it before using it.

The 404’s locale

A locale @k8ordo/i18n’s declaration accepted is used for the render only when its pattern answers. When a declaration after it refuses, the locale accepted before is dropped too.

Under server mode and vite dev, when the id declaration refuses the shoes of /en/products/shoes, not-found.tsx renders the 404. The declarations above not-found.tsx are read again for it, so the 404 renders in the en its URL names. On /fr/nothing, where fr is not in the locale set, the [locale] declaration refuses, and the 404 renders in the default locale.

Under static mode every 404 is 404.html, written in the default locale. How it renders in the browser is covered in Deployment.

Values not in your data

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

import { findProduct } from '../../../lib/catalog.server';

export const params = field.object({
  id: field.integer({ min: 1 }),
});

export default async function ProductPage({
  params: { id },
}: PageProps<'/products/:id'>) {
  const product = await findProduct(id);
  if (product === undefined) notFound();
  return <h1>{product.name}</h1>;
}

A declaration checks only the shape of the value. Under server mode, for /products/999, which your data does not have, the page gives a 404 with notFound(). Under static mode a value no paths.ts returned is never written, and 404.html answers it, unless a fallback.tsx beside the page answers it with a page rendered in the browser (see “Values the build did not write”). A page that calls notFound() for a value a paths.ts returned stops the build (see “paths.ts errors”). What notFound() does is covered in Errors and redirects.

src/routes/products/page.tsx
import { href } from '@k8ordo/framework';

const ids = [1, 2, 3];

export default function ProductsPage() {
  return (
    <ul>
      {ids.map((id) => (
        <li key={id}>
          <a href={href('/products/:id', { id })}>Product {id}</a>
        </li>
      ))}
    </ul>
  );
}

The generated route table carries, per pattern, the type its declarations read. href() takes the same type the page receives, so href('/products/:id', { id: 42 }) takes a number. A string there is a type error.

href() writes the value into the URL as the one string the declaration reads back to the same value.

Layout params

A layout’s params are typed as strings even when it declares them.

At run time the value is a string too, as the type says. A layout receives the URL’s strings whether it wraps a page or not-found.tsx; only the page receives what the declarations read. When you need that value, take it in the page, or convert the string inside the layout.

[...name] parameters

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

export const params = field.object({
  path: field.list(
    field.string({ pattern: '[a-z0-9]+(?:-[a-z0-9]+)*' }),
    { max: 4 },
  ),
});

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

The parameter of a [...path] directory is an array of segments. A declaration reads it with field.list(), each segment as the kind inside it, and min and max count the segments. The params.path the page receives, and the value a link takes, are the array the declaration read.

A path with one segment the declaration refuses, or with more segments than max, is one this directory does not answer. /docs/Guide and /docs/a/b/c/d/e are answered by the nearest not-found.tsx, under a 404.

[...name] is server mode only. For the rules of the directory, see Routing.

Values from paths.ts

src/routes/products/[id]/paths.ts
import type { Paths } from '@k8ordo/framework';

import { listProducts } from '../../../lib/catalog.server';

const paths: Paths<'/products/:id'> = async () =>
  (await listProducts()).map((product) => product.id);

export default paths;

Static mode only. A build cannot invent parameter values, so the parameter’s directory holds a paths.ts. Its default export is a function that returns the values of that parameter, as an array or a promise of one. Routes without parameters come from the route table and need nothing.

Type it with Paths from @k8ordo/framework; its type argument is the pattern down to that directory. A paths.ts runs in the same environment as the pages, so it can import a server-only module and use the application’s aliases. It reads the same module instances as the pages, so data one of them cached is shared.

Return each value as a link’s href() takes it. When the page’s declaration reads the parameter as a number, return the number; without a declaration, any string, number, bigint or boolean works. The build spells it as href() does, with String(), and escapes it for the URL, so return café or a b as it is. An empty string is refused.

The values apply to everything below the directory. The page.tsx beside it, and every page, route.ts and redirect.ts in the directories below, are written once per value. With blog/[slug]/paths.ts, blog/[slug]/og.png/route.ts needs no list of its own.

Server mode does not read a paths.ts. Values come from the request, so growing data needs no rebuild, and the same routes/ works under either mode.

Locale values

src/routes/[locale]/paths.ts
import type { Paths } from '@k8ordo/framework';

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

const paths: Paths<'/:locale'> = () => locales.all;

export default paths;

In the locale directory, return locales.all from @k8ordo/i18n. Every page below [locale] is then written once per locale. How locales is defined is described on Locales.

This site’s src/routes/[locale]/paths.ts is the same file. Each URL is rendered as a request of its own, so its messages use that URL’s locale.

Parameters above

src/routes/[locale]/posts/[id]/paths.ts
import type { Paths } from '@k8ordo/framework';

import { listPosts } from '../../../../lib/posts.server';

const paths: Paths<'/:locale/posts/:id'> = async ({ locale }) =>
  (await listPosts(locale)).map((post) => post.id);

export default paths;

The function receives the parameters of the directories above it as the layouts above read them: each value the paths.ts above returned, spelled as the URL carries it, then read again by the params exports of the layouts in the directories above this one, outer first. The page beside it and a layout in its own directory take no part, since they may read this directory’s parameter, which has no value yet. When [locale]/layout.tsx’s declaration reads the locale, locale is that locale. When [year]’s layout reads it with field.integer(), year arrives as the number 2024 even if the paths.ts above returned '2024'. A parameter no such declaration reads stays a string. The build calls it once per combination of their values. Here it returns the post ids for ja, and again for en.

When the directory of a parameter above has no paths.ts, the build cannot call the one below and stops. Give that directory a paths.ts too.

paths.ts errors

The build stops when a paths.ts hits any of these. Each error message names the file, pattern or URL at fault.

  • A parameter no paths.ts returns values for: static build needs the values of /tags/:tag — a paths.ts in each parameter's directory returns them, …
  • A return value holding something with no URL spelling: tags/[tag]/paths.ts has to return an array of the values of :tag, each a non-empty string, a number, a bigint or a boolean
  • A paths.ts below a parameter that has none: [locale]/posts/[id]/paths.ts is asked for its values once per value of the parameters above it, and /:locale/posts still holds one — …
  • A paths.ts below a value a layout’s declaration refuses: the paths.ts files stand where a params declaration refuses the values above them, so they were not asked: /last/:slug ([year]/[slug]/paths.ts)
  • A value a declaration refuses: a paths.ts returned values a params declaration refused: /products/shoes
  • A value whose page calls notFound(): a paths.ts returned values whose page called notFound(): /products/3
  • A value of !fallback: a paths.ts returned !fallback, which the build keeps for shells: /posts/!fallback
  • A value of ..: a pathname to write leaves the output: /products/..
  • A paths.ts in a directory that is not a [param] one: paths.ts gives the values of its directory's parameter, and "posts" is not a [param] directory — …

Values the build did not write

src/routes/posts/[id]/fallback.tsx
import { Suspense } from 'react';

import { PostFromUrl } from '../../../components/post-from-url';

export default function PostFallback() {
  return (
    <Suspense fallback={<p>Loading the post…</p>}>
      <PostFromUrl />
    </Suspense>
  );
}
src/components/post-from-url.tsx
'use client';

import { notFound, useMatch } from '@k8ordo/framework';
import { use } from 'react';

import { readPosts } from '../lib/posts';
import { PostArticle } from './post';

export function PostFromUrl() {
  const match = useMatch('/posts/:id');
  if (match === null) return null;
The URL moved before the next page arrived
  const post = use(readPosts()).find(
    (each) => String(each.id) === match.id,
  );
  if (post === undefined) notFound();
  return <PostArticle post={post} />;
}
src/lib/posts.ts
import type { Post } from '../components/post';

const API = 'https://api.example.com/posts';
let posts: Promise<readonly Post[]> | undefined;

export const readPosts = (): Promise<readonly Post[]> =>
  (posts ??= fetch(API).then(async (response) => {
    if (!response.ok) throw new Error(response.statusText);
    return (await response.json()) as readonly Post[];
  }));

Static mode only. Put a fallback.tsx beside a page.tsx, and it answers every URL whose value no paths.ts returned. It is for values the build cannot know, such as posts published after it ran. Server mode never renders it: there page.tsx renders every value per request. Its placement is checked in both modes.

The build writes a page holding the layouts with fallback.tsx inside them: the shell. The host answers /posts/3, which has no file, with the shell, and the browser reads the value from the URL and renders the post. The build writes the rewrite rules for this into _redirects; setting up the host is covered in Deployment.

PostArticle is the one the page uses. readPosts reads the list of posts from the API in the browser, and the promise it hands use() is made once and reused, never once per render.

What it receives

A fallback.tsx receives no props: a shell has no value to give it. It may be a Server Component or a 'use client' one. A Server Component runs at build time, so it renders the same thing for every value.

A Client Component reads the value. Inside a shell, whatever reads useMatch or usePathname is left to the browser by the server render, so the HTML holds the fallback of the <Suspense> in fallback.tsx. useMatch returns null when the URL has moved before the next page arrived; render nothing then.

A page’s params is not read for a shell. The host answers every URL that fits the pattern with the shell, /posts/abc as much as /posts/3, so look the post up by the URL’s spelling, String(post.id) === match.id, and call notFound() when there is none. A layout’s params is read, over the parameters the shell fills, which is why the locale’s declaration belongs on a layout rather than a page.

Where shells go

text
src/routes/
  [locale]/
    paths.ts
    layout.tsx
    posts/
      [id]/
        paths.ts
        page.tsx
        fallback.tsx

The build writes one shell per value the paths.ts files above return. Here [locale]/paths.ts returns ja and en, so there are two shells, at /ja/posts/:id and /en/posts/:id. No shell answers /fr/posts/1.

A paths.ts may sit in the same directory as the fallback.tsx. The values it returns are written as pages, and the shell answers the rest. Without it, the shell answers every value.

With no parameter above, there is one shell. The build makes it from the pattern and writes it at /posts/!fallback/.

When a layout above, such as [locale]/layout.tsx, receives a parameter, the shell needs that value too, since the layout is written as HTML. Without a paths.ts in that parameter’s directory, the build stops.

A fallback.tsx answers only for the page.tsx beside it. A route below it, such as /posts/:id/comments, is written for the values posts/[id]/paths.ts returns and no others, unless it is a page with a fallback.tsx of its own.

Information

Note

vite dev answers as the built site will. A value no paths.ts returned gets the shell where there is a fallback.tsx, and a 404 otherwise. A request for a value it does not know makes it call the paths.ts files again, so a value added to the data renders without a restart.

notFound() in a shell

When a Client Component in the shell calls notFound() while it renders, the nearest not-found.tsx renders in the page’s place, and the URL stays. The build rendered that not-found.tsx along with the shell, so nothing more is requested. Since it is the same for every value, a not-found.tsx that would receive a parameter the shell leaves to the browser, such as one beside the fallback.tsx, is passed over for the nearest one above it. It also receives the shell’s pathname (/ja/posts/!fallback), so read the visitor’s URL in a Client Component when it shows it.

The host has already answered with the shell under a 200, though, so a value your data does not have still gets a 200. And notFound() works only during render: called from an effect or an event handler, no boundary sees it.

Shell errors

The build stops when a shell’s location or its render goes wrong:

  • A shell under a parameter that a layout above receives and no paths.ts gives values for: these shells leave out a parameter a layout above their fallback.tsx receives, so its directory needs a paths.ts: /:locale/posts/:id (…)
  • A shell below a value a layout’s declaration refuses: the shells stand where a params declaration refuses the values above them: /xx/posts/:id
  • A shell that would also answer URLs a route declared earlier is for: the shell for /ja/posts/:id ([locale]/posts/[id]/fallback.tsx) would also answer …
  • A shell that calls notFound() while the build renders it: the shell for /ja/posts/:id called notFound() while it rendered, …
  • A shell another route answered: the shell for /ja/posts/:id (…) was answered by …

How to fix each is covered in Troubleshooting.

What a shell gives up

Compared with a page the build wrote, a value the shell answers gives up the following.

  • The body is rendered in the browser. No Server Component renders it per value.
  • The first HTML has no body, and no per-value <title> or OGP either, so a crawler that runs no JavaScript sees none of it.
  • A value your data does not have is still answered with a 200. Render <meta name="robots" content="noindex"> in not-found.tsx to keep it out of search results.
  • The data has to be on an API the browser can reach. If you set csp, add the API’s origin to connect-src.
  • Layouts receive the shell’s URL, /posts/!fallback, as pathname. Render anything made from the URL, such as a canonical link or hreflang, in a Client Component. The build warns when !fallback is left in the HTML.
  • It needs a host that rewrites. On GitHub Pages, a value the build did not write gets 404.html.
src/routes/products/page.tsx
import type { PageProps } from '@k8ordo/framework';

import { ProductList } from '../../components/product-list';
import { fetchProducts } from '../../lib/catalog.server';
import { listState } from '../../lib/list-state';

export const search = listState.url;
The query declaration this page reads

export default async function ProductsPage({
  search,
}: PageProps<'/products'>) {
  const products = await fetchProducts(search);
Fetches by the values read
  return <ProductList products={products} />;
}

Server mode only. A page declares the query it reads by exporting its declaration as search, and receives the values read as search. A layout, and a page that does not declare search, never receives the query.

A missing parameter takes its default, and a value its field refuses resets that field alone to its default. The search export is the url declaration of a definePageState from @k8ordo/state, so the application depends on @k8ordo/state. Defining one is described on URL.

Use the values to fetch, and pass nothing on to a Client Component. The framework seeds every page’s states with the request’s query, so useAppState(listState) returns the URL’s values from the server render on. A navigation that changes the query loads that page again in place; nothing remounts, and the scroll position stays. On back and forward, the scroll position returns to where that entry was left once the page loaded again is on screen.

k8ordo

React libraries that use Baseline features without holding back.