@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.
380 lines (304 loc) • 18.8 kB
Markdown
# Edge caching
> Serving prerendered pages, PPR shells and kept pages from a CDN, the headers they go out with, and purging by tag.
A page that exports `revalidate` can be kept by a CDN and served to everyone
without touching your origin:
```tsx title="src/app/posts/[slug]/page.tsx"
export const revalidate = 60 // seconds a shared cache may keep it
```
```
Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=86400, stale-if-error=86400
CDN-Cache-Control: max-age=60, stale-while-revalidate=86400, stale-if-error=86400
ETag: "…"
```
Prerendered pages and PPR shells are files, and can sit on a CDN too. This page
covers the headers each one goes out with, purging a CDN when data changes, and
serving shells from the edge. [ISR](/guides/isr) is the how-to for
`revalidate` itself.
## Caching a page at a CDN
Export `revalidate` from the page, in seconds. The page is rendered whole, and
when the render read nothing that belongs to one visitor, it goes out public:
- A CDN keeps it for `revalidate` seconds, then refreshes it in the background.
A browser never keeps it.
- While your origin is down, erroring or mid-deploy, a CDN that reads
`stale-if-error` serves its copy for up to a day rather than the error.
- A cache revalidating a copy that hasn't changed is answered `304`.
- A 404, including the `not-found.tsx` a navigation shows, is kept for at most
a minute, so a scanner walking random URLs can't hold your pages out.
The value must be a number literal the build can read. A layout can export it
too: the smallest value on the way down to the page wins, and `0` anywhere
means the page is rendered per request. The page is not prerendered:
`revalidate` says its data changes, so a frozen copy would be wrong from the
first change.
rsc-kit sends `CDN-Cache-Control` (RFC 9213), so a CDN that reads it can cache
pages. Cloudflare does. Homeport's edge caches on nothing else, and strips it
before the answer leaves, so you won't see it in a browser there.
`CDN-Cache-Control` goes out only when a purge can reach the CDN:
`CDN_PURGE_URL` is set, or a purge is installed with `installPurge()`. An edge
that keeps pages on that header alone then never holds a copy `changed()`
can't take back. Without one, `Cache-Control`'s `s-maxage` still gives a cache
that reads it the same lifetime. The two headers always agree, and only a
public answer has either.
### A kept page calls its backend as nobody
Its host calls carry no cookie and no `Authorization`, and a cookie the backend
sets is dropped. `auth()->user()` is null there, as it is for every visitor a
shared copy is served to. A page that needs to know who is asking is not one to
keep.
A form in a kept page still posts as the visitor. The engine's actions, and
Laravel 13's forgery check, accept a same-origin post by its `Sec-Fetch-Site`
header, so it needs no token. A backend that still checks a token tied to the
session should be asked for it by a component that awaits `connection()`,
inside `<Suspense>`. In a static page that part is a hole filled per request
with the visitor's own session. In a `revalidate` page it is a read of the
visitor, so the page is sent private.
## Why a page was sent private
Any of these sends the page `private, no-store`, with a `Cache-Status` header
naming the reason and one line in the log per page and reason:
| `Cache-Status: rsc-kit; fwd=bypass; detail=` | Why |
| --- | --- |
| `cookies`, `headers`, `request`, `connection` | the render read the visitor: in the page, a layout, a Suspense'd child, metadata or `middleware.ts`. The log names the component |
| `host-middleware` | the route has host middleware, which runs against the visitor's session |
| `set-cookie` | the answer set a cookie |
| `nonce` | the answer carries a CSP nonce, which a shared copy would give everyone |
| `status` | only a 200 or a 404 is kept, never a redirect or a 5xx |
| `failed-render` | React reported a failure inside the payload |
| `payload-url` | a navigation's payload was asked for without its `?_rsc=` key, or a document with one; the router always adds it |
| `payload-shape` | a payload's `X-RSC` headers were not ones the router sends for this page: a held chain no page has, an intercepted navigation (its answer depends on the page it opened over), a made-up value. The key is a short hash, so such headers could be chosen to share another navigation's key |
## Purging a CDN when data changes
A page whose data comes through [`cache(fn, { tags })`](/guides/caching) sends
the tags of every answer it used:
```
Cache-Tag: posts,post:1
```
A CDN that purges by tag can drop its copy when one of them changes, rather
than waiting out `revalidate`. Install a purge, and `changed('posts')` calls it
with the names that changed, once the action's answer has gone:
```ts
import { installPurge } from '@rsc-kit/core/purge'
installPurge(async ({ tags }) => {
await fetch(`https://api.cloudflare.com/client/v4/zones/${zone}/purge_cache`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ tags }),
})
})
```
- **A purge that fails** is logged and never fails the change. The CDN still
drops its copy at the `max-age` in `CDN-Cache-Control`.
- **To send one yourself**, from a deploy step or a webhook, call
`purge({ tags, paths, all })`.
- **A path under a folder named in `subdomains`** is also sent as the path its
visitors use: `/merchant/orders` purges `/orders` as well.
- **A tag with a comma or a space** can't go in the header, and is left out
with a warning.
### With `CDN_PURGE_URL`
Set `CDN_PURGE_URL` and the purge is `cdnPurge()`, which posts
`{"tags": [...]}` there, unless you installed another. It is the only name
read, and it names neither this engine nor a platform, so a host can set it
for any framework. `RSC_PURGE_URL` and `HOMEPORT_PURGE_URL` are no longer read,
and `homeportPurge()` is now `cdnPurge()`, with no alias: set `CDN_PURGE_URL`
and change the import.
With a Laravel or Go backend, the change is made there, with `Rsc::changed()`
or `reg.Changed()`, and never passes through the engine. So the backend posts
the purge itself. Both do when `CDN_PURGE_URL` is set.
## Checking whether the CDN answered
To see whether the CDN answered, read `Cache-Status` (RFC 9211). A CDN that
sends it adds an entry under its own name, with `hit` when its copy answered.
`X-RSC-Kit` and `ETag` can't tell you: they were stored with the copy, so a hit
repeats them.
```sh
curl -sI https://example.com/posts/hello | grep -i cache-status
```
### `Cache-Status` on Homeport
Homeport's edge adds this entry from its next engine release. Until then a
response has no `homeport` entry.
The entry is named `homeport` and comes last, after any `Cache-Status` the app
sends. It is a separate header line, so `curl -I` can show two `Cache-Status`
lines, while `headers.get()` in `fetch` joins them with a comma.
| Answer | Value |
| --- | --- |
| Fresh copy | `homeport; hit; ttl=42` |
| Stale copy, refreshing in the background | `homeport; hit; ttl=-5; detail=stale` |
| Stale copy, app unreachable | `homeport; hit; detail=stale-if-error` |
| Stale copy, app answered 5xx | `homeport; fwd=stale; fwd-status=503; detail=stale-if-error` |
| From the app, being kept | `homeport; fwd=uri-miss; stored` |
| From the app, not kept | `homeport; fwd=uri-miss; detail=no-cdn-cache-control` |
| Cache switched off | `homeport; fwd=bypass; detail=off` |
| Preview | `homeport; fwd=bypass; detail=preview` |
| Not a GET or HEAD | `homeport; fwd=method; detail=request` |
| `Authorization`, `Range` or a request body | `homeport; fwd=bypass; detail=request` |
On the two "from the app" rows, `fwd` can also be `stale` or `vary-miss`:
`uri-miss` is only the plain case. A page that was not kept can also give
`no-store`, `private`, `no-cache`, `set-cookie`, `status` or `too-large` as its
`detail`.
- **Look for `hit` in the `homeport` entry**, not anywhere in the header: the
app's own entry can say `hit` too. The stale copy after a 5xx came from the
edge and doesn't say `hit`.
- **`stored` is not proof of a kept copy.** It is sent before the body, so a
body that fails or is too large can say `stored` and keep nothing. The next
request's `hit` is the proof.
- **A static page, a shell or an asset has no entry.** Those hits say
`X-Homeport-Edge: page`, `shell` or `asset`. Only `X-Homeport-Edge: cached`
is gone.
Homeport's edge is stricter than the page's headers alone. A page with more
than 128 tags, or a tag over 1024 bytes, is served but not kept there. So is
one that sends `Vary: Cookie` or `Vary: Authorization`, or names more than 16
headers in `Vary`, which a `revalidate` page only does if your own code adds
them.
## Kept by the engine, too
The host keeps a public `revalidate` page itself, with a CDN in front or not,
so it is served without a render on every host: a single server, several pods,
a Worker.
- A second request is answered from the kept copy, with `X-RSC-Kit: cached`
and an `Age` header. A document and each navigation's payload are kept apart,
and so are hosts and query strings.
- Past `revalidate`, the next visitor still gets the kept copy at once, and one
render replaces it behind them. The stale copy is served for the same day
`stale-while-revalidate` gives a CDN. After that, the page renders while the
visitor waits.
- **`changed(tag)` is seen at once, on every instance.** A kept page remembers
the version of every `cache()` tag it used, and a lookup checks them. After
`changed('posts')`, the next request for any page that read `posts` renders,
on every pod, with no purge sent anywhere, and is never served stale. A
render that was running when the change landed is kept, but never served.
- A burst of visitors to a page nobody has kept yet renders it once.
- Anything sent private is never kept.
A kept page lives in the store [`installCacheStore()`](/guides/caching)
installs, shared by every instance, or else in this process's memory, 64 MB and
10,000 pages at most, the least recently used going first:
| Where it runs | Where a kept page lives | What to install |
| --- | --- | --- |
| One server, a VPS | this process's memory | nothing |
| Several pods, Kubernetes | each pod's memory, or one Redis | nothing; `installCacheStore()` with Redis to render each page once for all pods |
| A Worker | KV | `installCacheStore()` with KV: an isolate's memory is gone in minutes, and the host warns without one |
| Vercel | Redis (Upstash) | `installCacheStore()`: a function's memory lives about as long. Vercel's CDN also keeps the page by `s-maxage` |
| Homeport | Homeport's edge | nothing: the engine keeps no copy there |
It is kept under its url with the query sorted, so `?a=1&b=2` and `?b=2&a=1` are
one copy, and without campaign tags - `utm_*`, `gclid`, `fbclid` and the rest an
edge ignores. A url with campaign tags is answered from the copy kept without
them; when there is none it renders for itself, and that render is not kept. A
page that shows something from `utm_source` should read it in the browser, or
not export `revalidate`.
On several instances, what keeps a change from being missed is the version
source, not the store. With a Laravel or Go backend, the backend keeps the
versions for every instance. An app without one installs a shared source, as it
already must for `refreshOn`. On a Worker or Vercel with no backend, that is
`sqlVersions()` on D1 or `postgresVersions()`, not KV, whose writes take up to a
minute to reach every location.
It is off in development, where a kept page would hide your edits, and on
Homeport, whose edge keeps the page instead. Turn it off with
`pageCache: false` in the host's options; `pageCache: { maxBytes }` sizes the
memory store.
## Serving prerendered pages from a CDN
The build writes every page it could prerender as a file:
```
build/static/
about.html a whole page
posts/hello.html likewise
posts/[slug].ppr.html a shell: static parts rendered, holes still empty
about.flight the payload for a client-side navigation
about.seg1.flight the same, for a client already holding one layout
```
Neither kind contains per-visitor data. They were rendered at build time, in no
request's context, which is what makes them safe for a shared cache. They go
out as:
```
Cache-Control: public, max-age=0, must-revalidate
```
Each carries an `ETag` of its bytes, so the check costs a `304` with no body
when nothing changed, from a CDN or from a browser coming back to the page.
A CDN in front holds the bytes but still checks with the origin every time. To
serve from the edge, add a cache rule for the paths you want held, with an edge
TTL. On Cloudflare that is a Cache Rule with *Edge TTL → Override origin*.
Cached responses carry a build version, so a new deploy doesn't leave old
shells served against a new payload.
A page rendered per request says `private, max-age=0, must-revalidate`: it may
have read the visitor's cookies, and its headers leave before the render could
say whether it did.
**Don't cache the whole site.** A route with middleware, a `middleware.ts` or
the host's `export const middleware = ['auth']`, is sent as
`Cache-Control: private, no-store`, because its content depends on who asked. A
zone-wide "cache everything" rule overrides that and serves one person's gated
page to everyone. Scope the rule to the paths you know are static.
## Finishing a shell at the edge
Request a PPR route and the document already contains its dynamic content: the
origin writes the shell first, then the boundaries it couldn't finish, into the
same response. A small inline script from React moves each hole into place as
the HTML parses, so the content appears without waiting for the app bundle or
hydration, and is in the HTML a crawler reads. With scripting off, the page
loads once more with everything in place, as [a page without
JavaScript](/guides/no-javascript#a-visitor-with-javascript-turned-off) does,
from an edge as from the origin.
To serve the shell itself from a CDN, an edge speaks the
[edge contract](/reference/edge-contract), the same one for every framework that
implements it. The build's `.output/edge.json` lists the pages with a shell and
the static pages, none of them under middleware. Two endpoints answer only a
caller holding the `EDGE_TOKEN` the origin was started with:
```
GET /_edge/page?path=/dashboard the static page, or the build-time shell
POST /_edge/resume?url=/dashboard a shell's holes, for this visitor
```
A static page goes out whole and never reaches the origin: its scripts and its
payload are immutable files under `/assets/`, so an edge that keeps those can
serve the page while the app is asleep.
[Pages an edge may serve from its cache](/hosts/deployment/build-output/#pages-an-edge-may-serve-from-its-cache)
says which pages rsc-kit lists.
[`examples/cloudflare-edge-worker`](https://github.com/rsc-kit/rsc-kit/tree/main/examples/cloudflare-edge-worker)
is a complete Cloudflare implementation, with no KV and no build step. Set the
same `EDGE_TOKEN` on the worker and the origin, and hand it the release's
`edge.json`. A miss goes to the origin while the page warms behind it, a static
hit is the page, and a shell hit streams the shell then pipes the resumed holes
onto the same response.
### With a Content Security Policy
Under a [Content Security Policy](/guides/content-security-policy), the
shells move from `shells` to `nonceShells` in `edge.json`. The holes resumed
into a shell are React's inline scripts, written for each request, and only a
nonce allows those. So only an edge that makes one per response serves them: it
asks with `Edge-Accept: nonce`, puts its nonce in the page's policy, and sends
it on the resume as `Edge-Nonce`. An edge that doesn't reads `shells` alone, and
your origin answers those pages. Static pages are listed either way, each with
its policy and its own hashes.
### Guarded routes are never cached
The shell endpoint answers `404` for any route that declares middleware, so a
guarded page never becomes a cache entry.
The resume endpoint runs that route's middleware against **the caller's own
cookies**, and refuses before rendering anything. An edge worker must forward
the visitor's request rather than making one of its own: a resume with no
cookies is an anonymous visitor and gets an anonymous answer.
## Behind an auth proxy
An auth proxy in front of the app can add a per-visitor response head the app
never sent. One with sliding expiry re-issues the session on an ordinary `200`,
so the response leaving your CDN carries a `Set-Cookie` this host never sent.
Marked `public`, that is one visitor's session handed to the next.
**Give any path your proxy covers a `middleware.ts`**, even an empty one. A
covered route is excluded from every cache decision: `private, no-store` on the
page, and refused outright by the shell endpoint.
You can't detect this by inspecting the response. Nothing added a
`Vary: Cookie`, and looking for `Set-Cookie` only catches the cookie version: an
`x-user-id`, a CSRF token or a locale header leaks the same way. Ask instead who
owns the response head on this route. It fails both ways, too: a session
leaking to the next visitor, or an anonymous response cached first and served
to someone who should have had a session, which looks like a flaky login.
## How it works
**Why "declares middleware" is a safe answer to "is this cacheable".** On this
host, a per-visitor response head can only come from middleware.
`responseHeaders()` and `cookies().set()` throw outside it, so a route with no
middleware has no way to acquire one. An auth proxy is the exception above.
**The resume takes a URL, not state.** Next's PPR protocol hands the postponed
state to the CDN and takes it back on the resume, so its resume endpoint parses
something an attacker can write, which is the shape of a known denial of
service. Here the endpoint takes a URL, and the origin reads its own state from
disk. A body posted to it is ignored.
**The response stays open until the holes finish.** Measured on a deployed
worker, for a page whose hole takes 2.5 s:
```
headers 55 ms
first body byte 56 ms
shell heading 56 ms ← the page is on screen here
fallback markup 56 ms
hole content 2549 ms ← same response, no second request
stream complete 2549 ms
```
The shell paints at the same moment either way, but `load` fires when the
slowest boundary resolves. Page metrics that key on `load` read differently,
and a proxy with a short response timeout needs to allow for the whole render
rather than just the shell.