@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.
97 lines (69 loc) • 2.91 kB
Markdown
# Rendering per request
> Marking work that belongs to the visitor, not to the build.
The build renders every page once and stores what it can. `connection()` marks
the work it shouldn't do: a query whose database the build can't reach, or a
value that has to differ per visitor.
```tsx title="src/app/orders/page.tsx"
import { connection } from '@rsc-kit/core/request'
async function Orders() {
await connection()
const rows = await db.query('select * from orders')
return <ul>{rows.map((r) => <li key={r.id}>{r.reference}</li>)}</ul>
}
```
During the build, `connection()` never resolves, so **nothing after it runs**:
the query isn't made, and the build needs no database. On a request it
resolves at once and the component runs as usual.
## Putting a boundary above it
Wrap the component that calls `connection()` in `<Suspense>`. The page around
it is stored, and the marked part arrives per request:
```tsx title="src/app/orders/page.tsx"
import { Suspense } from 'react'
export default function OrdersPage() {
return (
<>
<h1>Orders</h1>
<Suspense fallback={<p>Loading orders…</p>}>
<Orders />
</Suspense>
</>
)
}
```
If `connection()` is reached before anything has painted, there is nothing to
store, and the build refuses the route and says which fix to make:
```tsx
export default async function Page() {
await connection() // nothing above it has rendered
return <h1>{await something()}</h1>
}
```
A `loading.tsx` beside the page also works: it puts the whole page in one
boundary. See [Showing a loading state](/guides/routing#showing-a-loading-state).
## Calling it once
`connection()` is a barrier, not a wrapper. Everything after it in that
component belongs to the request, so one call is enough:
```tsx
await connection()
const orders = await db.orders()
await connection() // does nothing
const customers = await db.customers()
```
Call it once, before the work begins.
## When you don't need it
A query the build **can** run, whose answer is the same for every visitor,
doesn't need it. Let the build store the answer: that is the point of
prerendering, and marking it per request gives every visitor a render they
didn't need.
Use `connection()` when:
- the database or API isn't reachable from the build machine
- the value must differ per visitor
- the data changes faster than you deploy
- an [`rpc()` call answered at build](/hosts/backend-answered-pages/#answered-at-build-time)
should be asked per request instead
A page that reads `params`, `searchParams`, `headers()` or `cookies()` already
waits for the request, and needs no `connection()` for that part.
## Coming from Next.js
It has the same name and behaviour as Next's `connection()`. You'll need it
less often here: the build decides how to store each route by rendering it, so
most dynamic pages are understood without a marker.