# Static generation

> Rendering pages ahead of time, and exporting a site of files.

The build renders every page once and stores what it can, so a visitor gets a
file instead of a render. There is nothing to declare:

```bash
bun run build
#  ○  /
#  ○  /about
#  ◔  /account
#
#  2 stored, 1 shell
```

`○` is a page stored whole. `◔` is a shell: the parts that painted are stored,
and the parts waiting for the request are rendered per request and streamed in.

## How the build decides

The build renders each route and watches what happens:

| Outcome | What happened |
| --- | --- |
| The whole page | It rendered to completion. Stored and served from disk. |
| A shell | Something was still waiting when the time ran out, but the rest had painted. The shell is stored; the rest is rendered per request. |
| A redirect | The route only redirects, so the redirect itself is stored: status and location. |
| Refused | Nothing painted before the page blocked. The build fails. |

Each route gets 2 seconds; `RSC_PPR_TIMEOUT_MS` changes it. A page whose data
arrives in time is stored whole, including one that called `fetch()`. A page
that is only waiting steps aside for the next one, so hundreds of shells cost
about 2 seconds between them, not 2 seconds each.

A refused route has its boundary in the wrong place. Put the part that waits
inside `<Suspense>`, and the route becomes a shell. [Partial prerendering](/guides/ppr)
covers where boundaries go.

Whatever a stored page read during the build is in the file, what
[`rpc()` answered](/hosts/backend-answered-pages/#answered-at-build-time)
included, until the next build: a page stored whole is not refreshed by a tag.
If something should be current on every request, it has to read the request - `params`,
`searchParams`, `headers()`, `cookies()` - or call
[`connection()`](/guides/connection), which puts it behind a boundary instead
of in the stored bytes.

## Seeing why while you work

Under `vite dev`, every page has a small badge in its bottom-right corner
saying how production will answer it. Click it for the reasons:

```
◐ Not stored whole

The build stores a shell and streams what reads the request, if each read is
inside a <Suspense> or below a loading.tsx. A read above every boundary fails
the build.

• reads cookies() in Header
• calls rpc("Shared.user")

/account → app/account/page
Seen in this dev render. The build decides by rendering the page with no
request: `vite build` prints its verdict for every route.
```

It follows client navigation, and remembers whether you left it open.
Look at it before changing anything about caching: before adding
`connection()`, moving a read under `<Suspense>`, or exporting `revalidate`.

What it can say depends on the page:

| Badge | What it means |
| --- | --- |
| `○ Stored whole` | Nothing in this render read the request, so the build stores the page whole, as long as its data arrives within the 2 second budget. |
| `◐ Not stored whole` | Something read the request, and each read is listed with the component that made it. |
| `◐ Asks the backend` | The page calls `rpc()` and reads nothing else. The build asks the backend: an answer that is the same for everyone is stored, and a call that reads the visitor streams. |
| `○ Kept 60 s` / `ƒ Private` | The page exports [`revalidate`](/guides/isr). Development judges each render with the same check production makes, so this is the verdict itself, with the read or header that made it private. |

Development renders every page per request and runs no build, so outside a
`revalidate` page the badge reports what this render read, and says so. The
build's own output is the verdict. On a built server, the
[`X-RSC-Kit`](/guides/response-headers#headers-rsc-kit-sets) header says how
each response was actually served.

The badge lives in a shadow root, under Vite's error overlay, and works under
a [Content-Security-Policy](/guides/content-security-policy). It is never part
of a build. To turn it off:

```ts title="vite.config.ts"
rscKit({ devOverlay: false })
```

## Listing the URLs of a dynamic route

A route with a `[param]` is stored only for the values you list. Export
`generateStaticParams` from the page:

```tsx title="src/app/direct/[slug]/page.tsx"
import { Suspense } from 'react'
import { allSlugs, findPost, SECRET } from '../../../data'
import type { Metadata } from '@rsc-kit/core/metadata'

// Which urls exist. The one thing the build cannot work out for itself — and
// the reason this route is frozen per url, while /posts/[slug], which declares
// nothing, is frozen once as a shell.
export function generateStaticParams() {
  return allSlugs().map((slug) => ({ slug }))
}

export const metadata: Metadata = { title: 'Direct import' }

async function Body({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const post = await findPost(slug)

  // Referenced so the bundler cannot tree-shake the module away — the point is
  // that it is in the server graph and not the client one.
  const proof = SECRET.length

  if (!post) return <h1>No such post: {slug}</h1>

  return (
    <>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      <p className="muted">secret length on the server: {proof}</p>
    </>
  )
}

export default function DirectPage({ params }: { params: Promise<{ slug: string }> }) {
  return (
    <Suspense fallback={<p className="muted">Loading…</p>}>
      <Body params={params} />
    </Suspense>
  )
}
```

Each object it returns is one URL to build. For a route with several params,
return every combination:

```tsx title="src/app/blog/[year]/[slug]/page.tsx"
export function generateStaticParams() {
  return [
    { year: '2025', slug: 'hello-world' },
    { year: '2025', slug: 'getting-started' },
  ];
}
```

A route that lists nothing is rendered on demand instead. That is a choice,
not a failure.

### Listing a param once, in its layout

A layout can export `generateStaticParams` for the params of its own folder,
and every page beneath it is built for each value:

```tsx title="src/app/[locale]/layout.tsx"
export function generateStaticParams() {
  return [{ locale: 'en' }, { locale: 'fr' }];
}
```

`/en/about` and `/fr/about` are both stored, and `about/page.tsx` lists
nothing. A page with a param of its own still lists it, and receives the
values chosen above it:

```tsx title="src/app/[locale]/blog/[slug]/page.tsx"
export async function generateStaticParams({ params }: { params: { locale: string } }) {
  const posts = await postsIn(params.locale);

  return posts.map((post) => ({ slug: post.slug }));
}
```

It is called once per locale. See [Internationalisation](/guides/internationalisation).

## Keeping a page out of the build

There is no switch that turns prerendering off for the app. A page that must
not be stored says so where the work is, with [`connection()`](/guides/connection):

```tsx
await connection()

const rows = await db.query('select * from orders')
```

The build skips that read, stores everything around it, and the page still
gets a shell.

Prerendering **runs your application code**, so the build needs whatever that
code needs. A page that queries a database needs the database reachable from
the build, or `await connection()` before the query. A page that can't render
during the build is refused by name, so nothing that could have been stored is
quietly rendered per request instead.

To render every page per request, call `await connection()` in the root
layout and give every page a shell with a root `loading.tsx`. This is what
Next's `force-dynamic` on the root layout does. Every page then streams and
ships the runtime, and a page that could have been stored renders about five
times slower (measured in the repository's `bench/`). That cost is why it is
not the default.

Prerendering is off in watch mode.

## A value that must not be frozen

A stored page keeps whatever it rendered, including what the clock said
during the build:

```tsx
export default function Page() {
  // Frozen at the moment the build ran, for every visitor.
  return <p>Rendered at {new Date().toISOString()}</p>;
}
```

The build warns about it:

```
○  /
   ⚠  froze new Date() — a stored page keeps whatever that returned at build
      time. If it should differ per visitor, await connection() so the page
      renders per request; if only the browser needs it, use(browser()) keeps
      it out of the build entirely.
```

`new Date()`, `Date.now()`, `Math.random()` and `crypto.randomUUID()` are all
watched.

Wrapping it in `<Suspense>` changes nothing: the build renders straight through
a component that never waits, so the value is captured as before. A boundary
becomes a hole only when something inside it *waits* for what the build can't
finish - a read that outlasts the time limit, or `await connection()`.

Where the value is read decides what happens:

| The value is | Result |
| --- | --- |
| read in a server component | frozen during the build, and the build warns |
| read in a client component's body | produced twice, on the server and in the browser, and the two disagree |
| computed on the server, passed as a prop | sent with the page, so both renders read the same value (and it is frozen with the page) |
| read only in the browser | nothing on the server to disagree with |

Passing it as a prop is the usual answer for anything the server can decide:
right for a build stamp, wrong for a clock. For a clock, read it in the
browser only.

## Rendering something in the browser only

For a value that is per visitor and needs no server - a clock, `localStorage`,
a map, an editor - call `use(browser())`, and React skips the component on the
server:

```tsx
'use client';

import { Suspense, use, useState } from 'react';
import { browser } from 'react-dom';

function SavedDraft() {
  use(browser('the draft lives in localStorage'));

  const [draft] = useState(() => localStorage.getItem('draft') ?? '');

  return <p>{draft || 'Nothing saved yet'}</p>;
}
```

```tsx
<Suspense fallback={<p>Loading draft…</p>}>
  <SavedDraft />
</Suspense>
```

The page stays stored. The HTML has the boundary's fallback where the
component goes, and the browser renders the real thing in its place. Only one
side ever runs, so there is no mismatch.

- **The `<Suspense>` boundary is required.** Without one, the server render
  fails.
- **It must be a client component.** A server component has no browser render
  to fall back to.
- **Pass `browser()` to `use()`.** On its own it does nothing; don't throw it.

The reason is optional and only read on the server, where React's bailout
callback reports it. Give one anyway: it tells the next person why. Pass a
function if building it is expensive.

`browser()` is in `react-dom` 19.3, and replaces the old empty-first-render
plus `useEffect` pattern. rsc-kit has no `ClientOnly` component.

## Exporting a site

Build with `output: 'export'` to write a directory any static host can serve,
with no server at all:

```bash
RSC_OUTPUT=export npm run build
# Exported 9 pages to dist
```

- **Every route must be stored whole.** A shell on a static host would load
  and stay empty, since nothing runs to fill it in. The build refuses
  otherwise. `RSC_EXPORT_FORCE=1` writes the site anyway and lists what it
  left out, which helps you move an app towards exporting.
- **A route that only redirects** is written as a meta refresh, the one
  redirect every static host follows without configuration.
- **Everything served as a file comes along:** the browser bundle, `public/`,
  the icons and share image beside the root layout, the web manifest, the
  service worker, and stored `route.ts` answers such as `robots.txt`,
  `sitemap.xml` or a JSON feed.
- **A `route.ts` answer needs an extension in its URL.** A static host types a
  file by its extension, so `/api/health` would lose its `application/json`.
  The build lists it as left out rather than exporting it wrong. Use
  `/api/health.json`, or serve it from a host that runs.

## The document

The root `layout.tsx` renders the whole document; there is no separate HTML
template. The build adds the scripts and stylesheet links to it:

```tsx title="src/app/layout.tsx"
import './styles.css';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}
```

Load fonts and global CSS here. The root layout stays mounted across
navigations, so its `<link>` tags load once; the same tags in a nested layout
or page are added again on every navigation. Titles and meta tags come from
each page: see [Page metadata](/guides/metadata).

## What the build writes

Each stored route is a set of files named after its URL (`/` is `index`,
`/docs/install` is `docs/install`):

| File | For |
| --- | --- |
| `{key}.html` | A full page load. |
| `{key}.flight` | A navigation that replaces the whole document. |
| `{key}.seg1.flight`, `{key}.seg2.flight`, … | A navigation that keeps that many layouts, so the layouts above (and a half-filled form in them) stay mounted. |
| `{key}.meta.json` | The client chunks and build version the payload belongs to. |
| `{key}.ppr.html` | A shell, stored per route *pattern* rather than per URL. |

The server checks for a stored file before it renders, and renders when there
is none. The build writes them to `.output/server/rsc-static`. On other Nitro
presets they go wherever the server is deployed: inside the function on Vercel
(`.vercel/output/functions/__server.func/rsc-static`) and Netlify, and among
the static assets on Cloudflare, read through the assets binding.

`prerender` is also exported from `@rsc-kit/core/prerender` for running it
yourself. Its `write` option is a callback, since not every platform has a
filesystem; `writeTo` is the `node:fs` version. The build calls it for you, so
you shouldn't need it.
