UNPKG

@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.

295 lines (236 loc) • 12.1 kB
# Partial prerendering > Storing what every visitor sees the same, and rendering the rest per request. Most pages have markup that is the same for everybody and data that isn't. The build stores the first as a shell, and the rest is rendered per request and streamed into the same response: ```tsx title="src/app/posts/[slug]/page.tsx" import { Suspense } from 'react'; export default function PostPage({ params }: { params: Promise<{ slug: string }> }) { return ( <main> <nav>All posts</nav> <Suspense fallback={<Skeleton className="h-40" />}> <Post params={params} /> </Suspense> </main> ); } async function Post({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const post = await findPost(slug); return <article><h1>{post.title}</h1><p>{post.body}</p></article>; } ``` The nav and the skeleton are stored at build time and served from disk. The post is rendered when someone asks for it. There is nothing to switch on: every route is rendered by the build, and this is what it stores when part of a page waits. ## Where to put the boundaries Write the page as a plain synchronous component. Put each read in its own async component, under its own `<Suspense>`, with a skeleton the shape of what it stands for: ```tsx title="src/app/integrations/shopify/page.tsx" import { Suspense } from 'react'; import { ConnectButtonSlot } from './connect-button-slot'; import { ConnectionSlot } from './connection-slot'; import { ConnectionsSkeleton } from '../connections-skeleton'; export default function ShopifyPage() { return ( <Card> <CardHeader> {/* Fixed copy: in the shell, painted at once. */} <CardTitle>Shopify</CardTitle> <CardDescription>Connect your store so your agent can look up orders.</CardDescription> {/* Nothing to show until it knows: no fallback. */} <Suspense> <ConnectButtonSlot /> </Suspense> </CardHeader> <CardContent> <Suspense fallback={<ConnectionsSkeleton rows={1} />}> <ConnectionSlot /> </Suspense> </CardContent> </Card> ); } ``` ```tsx title="src/app/integrations/shopify/connection-slot.tsx" export async function ConnectionSlot() { const agent = await currentAgent(); // its own read, its own check const connection = await shopifyConnection(agent.id); return connection ? <ConnectionRow connection={connection} /> : <EmptyState />; } ``` - **The visitor sees the page, not a placeholder of it.** The heading and copy are in the shell. Only the parts that wait show a skeleton. - **Each part arrives when it's ready.** A fast read isn't held back by a slow one beside it. - **The skeleton can be exact.** It stands for one known thing, so nothing moves when the content lands. - **A slot is self-contained.** It does its own read and its own permission check, so it can move to another page, or be refreshed as a [section](/guides/sections). Only content inside a `<Suspense>` boundary can stream. Content above every boundary has to finish before anything paints, and a page with nothing to paint can't be stored. ## What makes a page dynamic Anything the build can't know: - **`await params`**, for a route that hasn't listed its URLs - **`await searchParams`**, the query string - **`await headers()` and `await cookies()`**, the request - **an `rpc()` call that reads the visitor**: their session, a cookie, who is signed in. One that doesn't is [answered at build](/hosts/backend-answered-pages/#answered-at-build-time) and stored, when the build has a backend to ask - **slow work of your own** that outlasts the build's time budget Each one suspends, the nearest fallback above it goes into the shell, and the real value arrives per request. `usePathname()` in a client component answers `""` in a shell for a route that hasn't listed its URLs: one shell serves every URL it matches, so no link is active and a breadcrumb is empty until hydration. In the browser the hook moves to the real URL on its own, with no mismatch to repair. Where the URL is known (a listed URL, a client navigation) it answers as always. A page whose data resolves inside the budget is stored **whole**, even one that called `fetch()`. To make a page reflect the world at request time, read the request; there is no flag. ## Making fallbacks look right Once a fallback has been on screen, React holds back the content that replaces it until 300 ms after that paint, even when the content arrived sooner. This is React's rule, not rsc-kit's. A stored shell and its holes arrive in one response, so with fast data the fallback often shows for the full 300 ms. On an installed app that's a flash of placeholders on every launch. - **Put a boundary only where the wait is real.** Data that is always back in a few milliseconds doesn't need a fallback. Rendered directly, it's in the first paint. - **Make the fallback the shape of the content.** The same card, size and colour with the numbers left blank reads as the page, not a flash. - **Leave out `animate-pulse` for anything usually gone quickly.** A pulse is what makes a short fallback look like a flash. ## Using loading.tsx Put a `loading.tsx` beside a page and the build wraps that page in `<Suspense fallback={<Loading />}>` for you, so the page can await at its top level: ```tsx title="src/app/posts/[slug]/loading.tsx" export default function Loading() { return <div className="h-6 w-50 rounded-lg bg-zinc-800" />; } ``` ```tsx title="src/app/posts/[slug]/page.tsx" export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; return <h1>{(await findPost(slug)).title}</h1>; } ``` It fits a page that is one read and nothing else, such as a detail page whose skeleton really is the page. Like `layout.tsx`, the nearest `loading.tsx` wins, and several in one chain nest: ```text src/app/ docs/ loading.tsx fallback for /docs/* [slug]/ page.tsx uses docs/loading.tsx ``` Elsewhere, prefer `<Suspense>` in the page: - **It hides what the page already knows.** The heading and copy wait with the data. - **The slowest read decides for all of them.** Everything under the one boundary paints when the last of it is ready. - **A status decided inside it isn't the response's.** A page under `loading.tsx` that calls `notFound()` or `redirect()`, or reads a backend that answers 404, may already have sent its shell with a 200. Decide whether a page exists for this visitor in [`middleware.ts`](/guides/authorization), which runs before anything is sent. - **It doesn't cover its layout.** It sits below the layout beside it, so a layout that waits needs a `<Suspense>` of its own. ### Don't put one at the root A root `loading.tsx` wraps every page, so a page that waits in the wrong place is still stored, behind the fallback the whole app shares. It looks exactly like a page whose boundary is in the right place, so the build warns: ```text ◐ /locale ⚠ nothing painted without the root loading.tsx — the fallback the whole app shares is standing in for this page. Put a boundary where the waiting is. ``` The build finds these by rendering the route a second time without the root fallback, and only for routes with no closer `loading.tsx`. Moving the boundary to where the waiting is fixes it. ## Branching on a param A route with params that listed no URLs has **one** shell for every URL, frozen with placeholders. The shape above a boundary can't depend on a param: ```tsx // Refuses to resume: two different components in one slot const { id } = await params return id === 'new' ? <CreateForm /> : <Record /> ``` React fills in the shell by position and component type, and a different component in a slot ends it: ```text Expected the resume to render <Record> in this slot but instead it rendered <CreateForm>. The tree doesn't match so React will fallback to client rendering. ``` Every hole then falls back to client rendering, and the page's buttons do nothing until it hydrates. Put the branch inside the `<Suspense>`, or give the route a `generateStaticParams` so each URL is frozen as itself. ## When the build can't store a route If nothing painted before the page blocked, there is no shell to store, and the build fails: ```text Some routes could not be prerendered: /dashboard — waits on rpc("Dashboard.summary") before anything can paint. Add a loading.tsx beside it, or put a <Suspense> above the waiting, and it has a skeleton to store. Each one reads request data — params, headers, cookies, or the host — above every Suspense boundary, so nothing can paint without it. Put the part that waits inside <Suspense>, or add a loading.tsx beside the page, so there is something to store while the rest arrives. ``` There is no way to declare it away. Moving the boundary is the fix. ## Changing the time budget `RSC_PPR_TIMEOUT_MS` sets how long the build waits on each page. The default is 2 seconds. Raising it lets slow pages be stored whole; lowering it turns more of them into shells. Pages don't wait in line for it. A page that has rendered what it can gives its place to the next, so a site of hundreds of shells costs about one budget, not one each. ## Deploying the shell and the server together A shell can only be finished by the server bundle from the same build. Every shell is stamped with its build, and a server that finds a shell from another build serves it but renders the page whole instead, with a line in the log. They usually drift apart through a Docker layer, CI cache or volume that keeps an old prerender output while the server is rebuilt. Build both together, or clear the output directory between builds. ## How it works ```text Build time → the page is rendered with a budget → anything still waiting when the budget expires is postponed → React has already flushed what did not need the request: layouts, static markup, and the Suspense fallbacks standing in for the rest → that markup is stored as the route's shell, and beside it, where it stopped Request time → the shell is served straight from disk — fast, no render → the render is picked up from where it stopped, against data that exists now → only the unfinished boundaries are written, onto the same response → a script React emits beside each one moves it into place as the HTML parses ``` - **Postponed, not abandoned.** An aborted render keeps only the bytes that flushed. A postponed one keeps a record of where it got to, which is what lets the boundaries be finished on the server and arrive with the document. The content is in the first response, before the app bundle or hydration, and in the HTML a crawler reads. With JavaScript disabled, the page loads once more with everything in place: see [a page with no JavaScript](/guides/no-javascript#a-visitor-with-javascript-turned-off). - **A slower hole, never a wrong page.** If the resume fails, the shell is served on its own and the client fills the boundaries when it hydrates. - **Rendered once per visit.** The payload the browser hydrates from streams into the document beside the HTML, so the page's queries and backend run once. A page stored whole fetches its stored payload, which costs no render. - **One shell per pattern.** `/posts/[slug]` has one shell for every slug. A `generateMetadata` streams under a boundary of its own, so the shell has a hole where the title goes; a route with static `metadata` has it in the shell. - **Component names are pinned.** The resume matches a slot by component name (`displayName`, then `name`). The build writes each component's name into the server bundle as a `displayName`, so a later bundler that renames bindings, or a page compiled into a single binary, still resumes. Two names for one component, as in `Expected the resume to render <J> in this slot but instead it rendered <J2>`, is the fingerprint of two builds.