# Routing

> File-based routes, route parameters, layouts, loading states and parallel slots.

A route is a folder with a `page.tsx` in it. The build reads your source tree
and finds every route itself, so there is no route file to register them in.

## Defining a route

The default source directory is `src/app`. A `page.tsx` there serves `/`:

```tsx title="src/app/page.tsx"
export default function HomePage() {
  return <h1>Welcome</h1>;
}
```

Every folder below it adds a segment to the URL:

```text
src/app/
  layout.tsx          wraps every page
  page.tsx            /
  about/
    page.tsx          /about
  docs/
    layout.tsx        wraps every page under /docs
    page.tsx          /docs
    sidebar.tsx       an ordinary component, not a route
    [slug]/
      page.tsx        /docs/:slug
```

Only a file named `page.tsx` makes a route. Anything else in the folder can be
imported by the pages beside it and is never served.

To keep your pages somewhere else, set `sourceDir` in the plugin options.

## Dynamic segments

Put a folder name in square brackets to capture that part of the URL. The page
receives it in `params`:

```tsx title="src/app/posts/[slug]/page.tsx"
export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;

  return <h1>{slug}</h1>;
}
```

`params` is a promise. Await it in the component that needs the value, so the
rest of the page can render without waiting for it.

A route can take several parameters, one per folder:

```text
src/app/teams/[team]/members/[member]/page.tsx    /teams/:team/members/:member
```

Each parameter needs its own name: `app/p/[id]/[id]` would lose the first
value, so the build refuses it. So are `[__proto__]`, `[constructor]` and
`[prototype]`, names every JavaScript object already has.

### Catch-all segments

`[...path]` captures the rest of the URL as one string, slashes kept:

```tsx title="src/app/files/[...path]/page.tsx"
export default async function FilePage({ params }: { params: Promise<{ path: string }> }) {
  const { path } = await params;  // /files/a/b/c → 'a/b/c'

  return <h1>{path}</h1>;
}
```

It also matches the URL with nothing after it: `/files` is this page with
`path` the empty string, unless a `files/page.tsx` is there to answer it. A
catch-all comes last - a directory after it is refused by the build - and
when two routes could answer a URL, the one that is more specific at the
first segment where they differ wins: a named directory over `[param]`, and
`[param]` over `[...rest]`.

### Query strings

A server component reads the query string from `searchParams`, which is a
promise in the same way:

```tsx title="src/app/search/page.tsx"
export default async function SearchPage({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
  const { q } = await searchParams;

  return <h1>Results for {q}</h1>;
}
```

A client component uses [`useSearchParams`](#reading-the-url-in-a-client-component)
instead.

## Layouts

A `layout.tsx` wraps every page in its folder and the folders below it. It
receives the page as `children`:

```tsx title="src/app/layout.tsx"
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <nav>…</nav>
        {children}
      </body>
    </html>
  );
}
```

Layouts nest. `/docs/routing` renders inside `docs/layout.tsx`, which renders
inside the root layout. Moving between two pages that share a layout keeps
that layout as it is, without rendering it again, so a half-typed search box in
it survives the navigation.

## Route groups

A folder name in parentheses groups routes without adding to the URL. Use it to
give some pages a different layout:

```text
src/app/
  (marketing)/
    layout.tsx        wraps /pricing and /about only
    pricing/
      page.tsx        /pricing
    about/
      page.tsx        /about
  (app)/
    layout.tsx        wraps /dashboard only
    dashboard/
      page.tsx        /dashboard
```

Two groups can't put a page at the same URL. `(home)/page.tsx` and
`(preview)/(home)/page.tsx` are both `/`, and the dev server and the build stop
with an error naming both files.

## Showing a loading state

Wrap the part of a page that waits in `<Suspense>`. Everything outside it
renders straight away, and the fallback shows until the waiting part is ready:

```tsx title="src/app/dashboard/page.tsx"
import { Suspense } from 'react';

export default function DashboardPage() {
  return (
    <>
      <h1>Dashboard</h1>
      <Suspense fallback={<Skeleton className="h-24" />}>
        <Revenue />
      </Suspense>
    </>
  );
}

async function Revenue() {
  const amount = await revenue();

  return <p>Revenue: {amount}</p>;
}
```

Give each part its own boundary, so a slow one doesn't hold up the rest. The
heading above is in the HTML the build stores, and only `Revenue` waits.

A `loading.tsx` beside a page wraps that whole page in one boundary. It suits a
page where nothing is worth showing until all of it is ready. Don't put one in
the root folder: it becomes the fallback for every page in the app, including
the ones that should have shown their own. [Partial prerendering](/guides/ppr#where-to-put-the-boundaries)
explains where boundaries go.

## Special files

| File | What it does |
| --- | --- |
| `page.tsx` | Makes the folder a route. |
| `layout.tsx` | Wraps the pages in its folder and below. Receives `children`. |
| `loading.tsx` | Wraps the page beside it in `<Suspense>` with this fallback. |
| `error.tsx` | What renders when the page throws. See [Errors](/guides/errors). |
| `not-found.tsx` | What renders for `notFound()` and unknown URLs. |
| `default.tsx` | What a parallel slot renders when nothing matches it. |
| `middleware.ts` | Runs before anything in its folder and below renders. See [Authorization](/guides/authorization). |
| `route.ts` | An API route instead of a page. See [API routes](/guides/api-routes). |

## Linking between pages

`Link` navigates without a full page reload:

```tsx
import Link from '@rsc-kit/core/Link';

<Link href="/about">About</Link>
```

Only the part of the page below the layouts both pages share is fetched and
rendered.

```tsx
// Start loading the page as soon as the link is on screen
<Link href="/dashboard" prefetch="mount">Dashboard</Link>

// Keep the scroll position instead of jumping to the top
<Link href="/docs/rsc" preserveScroll>Stay here</Link>

// Replace the history entry instead of adding one
<Link href="/settings" replace>Settings</Link>
```

| Prop | Default | What it does |
| --- | --- | --- |
| `href` | | Where to go. A URL on another site is left to the browser. |
| `prefetch` | `"hover"` | When to load the page ahead of the click: `"hover"`, `"mount"`, `"click"` or `"none"`. |
| `cacheFor` | `30000` | How long a prefetched page stays usable, in milliseconds. |
| `replace` | `false` | Replace the history entry instead of adding one. |
| `preserveScroll` | `false` | Stay where you are instead of scrolling to the top. |

Any other prop, `ref` included, is passed to the `<a>`.

To navigate from code, call `visit`:

```tsx
"use client";
import { visit } from '@rsc-kit/core/router';

await visit('/dashboard', { replace: true });
```

[Navigation](/guides/navigation) covers prefetching, progress and refreshing
the current page.

### Showing that a link is loading

A `Link` has a `data-pending` attribute while its page loads:

```css
a[data-pending] {
  opacity: 0.5;
}
```

To show it somewhere inside the link, use `useLinkStatus`:

```tsx
"use client";
import { useLinkStatus } from '@rsc-kit/core/useLinkStatus';

function NavLabel({ children }: { children: React.ReactNode }) {
  const { pending } = useLinkStatus();

  return <span className={pending ? 'opacity-50' : undefined}>{children}</span>;
}
```

## Typed links

`href` is checked against your routes, so a typo fails the typecheck:

```tsx
<Link href="/ordres">Orders</Link>
//          ^ Type '"/ordres"' is not assignable. Did you mean '"/orders"'?

<Link href={`/posts/${post.slug}`}>Read</Link>   // checked too
```

The same goes for `redirect()`, `visit()` and `Form`'s `action`. The build
writes the types to `.rsc-kit/rsc-routes.d.ts`, so a deleted page makes every
link to it stop compiling.

[Typed routes](/guides/typed-routes) covers lists of links, encoding a value
into a URL, and a URL computed at runtime.

## Reading the URL in a client component

`usePathname` and `useSearchParams` read the current URL and update when it
changes:

```tsx title="src/components/Filters.tsx"
"use client";
import { useSearchParams } from '@rsc-kit/core/useSearchParams';

export function Filters() {
  const q = useSearchParams().get('q');

  return <p>Showing results for {q}</p>;
}
```

On a page the build stores, the query string isn't known yet, so wrap the
component in `<Suspense>`. The stored page shows the fallback, and the browser
fills in the real value:

```tsx title="src/app/search/page.tsx"
<Suspense fallback={<p>Loading filters…</p>}>
  <Filters />
</Suspense>
```

A page rendered for each request answers with that request's query string, and
there is no fallback. `usePathname` needs no boundary: the path is known for a
stored page.

## Search params as state

For a filter or a tab kept in the URL, use [nuqs](https://nuqs.dev) with this
adapter in the root layout:

```tsx title="src/app/layout.tsx"
import { NuqsAdapter } from '@rsc-kit/core/nuqs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return <NuqsAdapter>{children}</NuqsAdapter>;
}
```

```tsx
const [kind, setKind] = useQueryState('kind');
```

With `shallow: false`, a change renders the server components again with the
new query, and client state on the page is kept. nuqs's own
`nuqs/adapters/react` reloads the whole page in that case.

`nuqs` is an optional peer dependency. Once nuqs ships an adapter for rsc-kit,
this import will point to it.

## Parallel routes

A folder whose name starts with `@` is a slot. It renders beside the page and is
passed to the layout in the same folder as a prop of that name:

```text
src/app/
  layout.tsx          receives { children, sidebar }
  page.tsx            children
  @sidebar/
    page.tsx          sidebar
```

```tsx title="src/app/layout.tsx"
export default function Layout({ children, sidebar }: {
  children: React.ReactNode;
  sidebar: React.ReactNode;
}) {
  return (
    <div className="flex">
      <aside>{sidebar}</aside>
      <main>{children}</main>
    </div>
  );
}
```

A slot adds nothing to the URL. Give it a `default.tsx` for the URLs it has no
page for. Render every slot the layout receives: one that isn't rendered is
left out of the page without a warning.

[Route interception](/guides/route-interception) uses slots to open a page in a
modal.

## When the build can't store a route

The build renders every route and stores what it can: the whole page, or a
shell with the waiting parts filled in per request. A route that reads
`params`, cookies or headers before anything can paint has nothing to store,
and the build fails with the fix:

```text
Some routes could not be prerendered:

  /photo/[id] — renders its params before it can paint, and lists no urls to build
```

Wrap the part that reads the request in `<Suspense>`, or list the URLs to build
with `generateStaticParams`. [Static generation](/guides/static-generation)
and [Partial prerendering](/guides/ppr) cover both.
