@rsc-kit/mcp
Version:
An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.
221 lines (161 loc) • 7.98 kB
Markdown
# Typed routes
> Links that fail the typecheck instead of the browser.
Every build writes the URLs it found to `.rsc-kit/rsc-routes.d.ts`. `Link`,
`visit`, `prefetch`, `redirect` and `Form` accept only those:
```tsx
import Link from '@rsc-kit/core/Link'
<Link href="/about">About</Link> // ✅
<Link href="/abuot">About</Link> // ❌ typecheck fails
```
A link to a page you renamed or deleted stops compiling, instead of becoming a
404 someone finds after you deploy.
## Linking to a dynamic route
Use an ordinary template literal:
```tsx
<Link href={`/posts/${post.slug}`}>{post.title}</Link> // ✅
<Link href={`/postz/${post.slug}`}>{post.title}</Link> // ❌
```
There is no `route()` helper. A template literal is already checked the way a
builder would check it.
Encode a value that isn't yours. `` `/posts/${'a / b'}` `` type-checks, but it
means three path segments:
```tsx
<Link href={`/posts/${encodeURIComponent(slug)}`}>…</Link>
```
## Typed search params
A page that [exports a `searchParams` schema](/guides/url-validation) types
every link to it:
```tsx title="src/app/search/page.tsx"
export const searchParams = z.object({
q: z.string().default(''),
page: z.coerce.number().int().min(1).default(1),
});
```
```tsx
<Link href="/search" search={{ q: 'shoes', page: 2 }}>Page 2</Link>
<Link href="/search" search={{ sort: 'asc' }}>…</Link> // does not compile: the page never reads sort
<Link href="/search" search={{ page: '2' }}>…</Link> // does not compile: page is a number
```
- **A required key is required on the link.** A `q: z.string()` with no default
makes `search` itself required, so a missing `q` is caught by the compiler,
not by the page's error boundary.
- **Values are typed by what the page sees.** `z.coerce.number()` accepts
anything, but the link takes a number. Whether a key is required comes from
the schema's input; its type comes from the output.
- **Arrays repeat the key.** `tags: ['a', 'b']` becomes `?tags=a&tags=b`, which
is what `z.array()` parses back.
- **A page with no schema takes any scalars**, and so does an href that isn't
one route (`path as Route`), because there's nothing to check it against.
For `visit()`, `prefetch()` and anything else that wants a string, `href()`
runs the same check:
```ts
import { href } from '@rsc-kit/core/routes';
visit(href('/search', { q: 'shoes', page: 2 }));
redirect(href('/search', { q: 'shoes' }));
```
## A list of links
TypeScript widens an array's `href` to `string` unless you say what it is. Use
`satisfies` with `Route`:
```tsx
import type { Route } from '@rsc-kit/core/routes'
const nav = [
{ href: '/', label: 'Home' },
{ href: '/about', label: 'About' },
] satisfies { href: Route; label: string }[]
nav.map((item) => <Link key={item.href} href={item.href}>{item.label}</Link>)
```
Without `satisfies`, `href` is a `string` and you lose the check.
## A URL computed at runtime
A destination read from a cookie or handed over by middleware is a string the
compiler can't check. Cast it, and you vouch for it:
```ts
redirect('/login'); // ✅
redirect('/logn'); // ❌
redirect(returnTo as Route); // computed: you vouch for it
```
A redirect's `search` is checked too, against the destination's own
`searchParams` schema. See [redirects](/guides/redirects/#with-a-query-string).
## Fetching an API route
A `route.ts` is a `Route` as well, so `<Link href="/logout">`,
`visit('/agent-account')` and `redirect('/files/export.csv')` all typecheck.
For `fetch`, wrap the URL in `apiUrl`. It accepts only `route.ts` URLs, so a
fetch to an endpoint that no longer exists stops compiling:
```ts
import { apiUrl } from '-kit/core/routes'
await fetch(apiUrl(`/api/orders/${id}`))
await fetch(apiUrl('/api/ordrs')) // does not compile
await fetch(apiUrl('/orders')) // does not compile: that's a page
```
`apiUrl` returns what it was given. It exists because `fetch` takes any
`string`, so without it there's nowhere to put the type. A page URL doesn't
compile, because fetching a page gets HTML where JSON was expected.
This checks the URL, not what the endpoint returns. API routes are plain web
standards, with nothing of ours in them. For types end to end, a [server
action or query](/guides/queries/) is already typed across the boundary: the
return type is the function's.
The browser treats a link to a `route.ts` as an ordinary anchor. It is never
prefetched, since a hover must not sign someone out, and clicking it is a full
navigation rather than a payload fetch.
## The backend's urls
A prefix named in `backendPaths` is a `Route` too, so a link or a redirect to a
URL the backend owns compiles as written:
```tsx
// vite.config.ts: rscKit({ backendPaths: ['/gitlab'] })
<Link href="/gitlab/connect">Connect GitLab</Link> // ✅
redirect('/gitlab/connect'); // ✅
<Link href="/gitlabs">…</Link> // ❌ not the prefix
```
A dynamic segment in one matches any string. `backendPaths: ['/login/[provider]']`
types `/login/google` and `/login/google/callback`, and leaves `/login` to the
page.
The prefix ends at a segment boundary, as it does on the server: `/gitlab`,
anything under it, and a query or fragment, never `/gitlabs`. Nothing past the
prefix is checked, because it's the backend's. Like a `route.ts`, the browser
loads it as a document and never prefetches it. See [leaving the
app](/guides/redirects/#leaving-the-app).
## Refreshing a section by name
`revalidate()` in an action and `refresh()` in the browser take a region name.
The names are typed to the ones the build found: every `section('orders', …)`,
every `` folder, `'page'` and `'all'`:
```ts
revalidate('orders') // a section the build found
revalidate('order') // does not compile
```
A name computed at runtime is cast, as an href is:
`revalidate(name as RevalidateTarget)`. A name the renderer doesn't know is
still refused, with the names it does know.
## Keeping the types current
The file is written whenever Vite starts: a build, or the dev server, which
also rewrites it when you add a route. A typecheck run without either, by an
agent or in CI, reads what the last start wrote. A link to a route added since
then fails with `"/admin"` is not assignable to type `Route`.
`rsc-kit-typegen` writes the file without starting Vite, from the app's own
`vite.config`. The scaffold's `typecheck` and `check` scripts run it first. In
an older project, add it the same way:
```json title="package.json"
"typecheck": "rsc-kit-typegen && tsc --noEmit"
```
## The build checks
`vite build` runs the project's typecheck before it bundles, and stops on an
error. A link to a route that doesn't exist is a failed build. It's the same
`tsc --noEmit` the `check` script runs, on the same tsconfig, and it takes
about a second.
```ts title="vite.config.ts"
rscKit({ typecheck: false }) // turn it off
```
A project with no `tsconfig.json`, or without `typescript` installed, is
skipped.
## Limits
- **A dynamic segment widens.** `/posts/[slug]` becomes `` `/posts/${string}` ``,
so `/posts/a/b` type-checks even though it doesn't match at runtime.
- **Without the generated file, nothing is checked.** If
`.rsc-kit/rsc-routes.d.ts` is missing, or your tsconfig's `include` doesn't
cover `.rsc-kit`, every URL prop accepts any `string` and nothing breaks.
There's no flag to turn the check on; the file is the switch.
## How it works
The build writes one line per route into `rsc-routes.d.ts`. For a page with a
`searchParams` export, that line reads the export's type from the page module.
Nothing runs, and a page without the export costs nothing. The build also
writes the `route.ts` files into their own narrower union, `ApiRoute`, which is
what `apiUrl` takes, and hands the client every route's pattern so it knows
which links to treat as documents.