You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 35c0ae5
Browse filesBrowse the repository at this point in the historyBrowse files
fix(router)!: ctx.request.headers and getRequestContext().cookie()/cookies() refuse where cookies() does (#976) (#999)
The identity guards covered cookies(), headers(), the theme reads and a
{ cache: false } variable, but three raw reads went around them:
ctx.request.headers (the same Request in handlers, middleware, loaders and
getRequestContext().request) and getRequestContext().cookie()/cookies().
A "use cache" function keys a ctx or Request argument by route and URL
only, so a header read in its body stored the first caller's value for
every caller; a handler under cache() or on a ppr route stored it in the
shared record or shell, and a loader's own cache() without key() stored it
in its entry.
- The request every ctx exposes gets an own, non-enumerable headers getter
(server/request-headers.ts shadowRequestHeaders, guarded by
cookie-store.ts guardRequestHeaders) that runs guardIdentityRead: the
same scopes, order and error style as headers(), and recorded at the
read for a loader cache() fill. createRequestContext installs it, and
createHandlerContext for a request the router builds and matches (the
progressive-enhancement re-render, a navigation-only capture). No Proxy:
fetch(ctx.request) and new Request(ctx.request) copy the headers natively
and never call the getter (they are not guarded; the docs say not to
make them in a cached body). clone() is shadowed to return a guarded
clone. A lazy srvx NodeRequest's _request (Node dev and preview servers,
vercel output) and Node's util.inspect hook run with the guard off, so
srvx's own clone/body reads and console.log(ctx.request) are not reads;
the facade stays lazy, so a buffered rawBody is still read.
- Router code reads a request's headers only through requestHeaders(),
which bypasses the getter (state cookie rotation, request
classification, HMR and prefetch markers, origin guard, cf-ray, ...).
- getRequestContext().cookie()/cookies() run guardRawCookieRead; the
cookies() store reads the unguarded _readCookie()/_readCookies().
- key(), a store keyGenerator, condition(), tags() and onError run under
runIdentityExempt (cache/cache-exec-scope.ts): identity reads there are
allowed and record nothing. A ppr capture resolves its doc record key
and the record's tags again under the capture context, so a
keyGenerator or tags() reading the request (or cookies()) refused every
capture of its route. The exemption is async-local, so a "use cache"
body, a loader body and a segment funnel end it on entry: a key() that
awaited a cached function reading cookies() stored the first visitor's
cookie.
Breaking: a handler under cache() or on a ppr route, or a "use cache"
body, that reads ctx.request.headers (or a clone's headers) now throws or
refuses the capture. Copy the value in middleware (ctx.set) and include it
in key(), read it in a live loader, or pass it into the "use cache"
function as an argument. The test fixtures and the test-app,
cloudflare-basic and vite-rsc-demo pages that rendered a partition header
from a cached handler now render the middleware copy; vite-rsc-demo's
unreferenced PostRoute is removed.
getRequestContext().theme has been guarded since #979.
Tests: request-headers.test.ts (the getter; fetch, new Request, clone and
util.inspect in every refusing scope on undici; the srvx facade, lazy
rawBody; onError), identity-exempt-scope.test.ts (a cached body, loader
body and funnel started inside an exempt callback are guarded), the SCOPES
table in cookie-store.test.ts (three new surfaces, exempt rows, clone
recording), request-raw-reads.rsc-test.tsx through serveShellRequest
(keyGenerator, condition() and tags() at capture), and dev + production
e2e identity-raw-reads in the router test-app and cloudflare-basic (on
workerd, fetch, new Request and clone inside a cache() boundary).
Copy file name to clipboardExpand all lines: apps/docs/content/docs/rango/concepts/freshness.mdx
+3-3Lines changed: 3 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -78,12 +78,12 @@ That loader exemption is also the default contract of `cache()`: cached UI plus
78
78
79
79
Rango's caches are built so a hit can't serve another user's data or lose a response side effect. Two guard models, both blocking anything that would be wrong on a hit:
80
80
81
-
-**`cache()` boundary guard** — fires while the handler runs on a miss. `cookies()`, `headers()` and the visitor's theme (`ctx.theme`, `getRequestContext().theme`) throw (request-scoped data would bake into the shared shell); response side effects such as `ctx.headers.set()` and cookie writes throw even on a miss, because they'd be skipped on a hit and produce inconsistent responses. `ctx.set()` of a cacheable var is allowed — children are cached too and can read it.
81
+
-**`cache()` boundary guard** — fires while the handler runs on a miss. `cookies()`, `headers()`, the raw reads `ctx.request.headers` and `getRequestContext().cookie()` / `.cookies()`, and the visitor's theme (`ctx.theme`, `getRequestContext().theme`) throw (request-scoped data would bake into the shared shell); response side effects such as `ctx.headers.set()` and cookie writes throw even on a miss, because they'd be skipped on a hit and produce inconsistent responses. `ctx.set()` of a cacheable var is allowed — children are cached too and can read it.
82
82
-**`"use cache"` exec guard** — the same request-scoped APIs (the theme reads included) and response writes throw inside the cached function, plus `ctx.set()`, `ctx.setTheme()`, `ctx.setLocationState()`. The guard runs only on the cached path: with no store configured the function runs uncached and nothing throws.
83
83
84
-
Loaders are exempt from both — they always run fresh, so read request data there. Headers that must appear on every response belong in middleware, outside any boundary.
84
+
Loaders are exempt from both — they always run fresh, so read request data there. Headers that must appear on every response belong in middleware, outside any boundary. A cache's own callbacks — a `key()`, a store `keyGenerator`, a `condition()`, a `tags()` function — read request identity freely in every scope: the value picks or labels the entry, it isn't rendered into it. A `"use cache"` function or loader they call is guarded as usual. To render a value a `key()` partitions by, copy it in middleware with `ctx.set()` and read `ctx.get()` in the handler.
85
85
86
-
A loader bound with its own `cache()` is the one loader that doesn't run fresh: its value is stored under the loader, host, path and params. A miss whose body read `cookies()`, `headers()` or a non-cacheable `ctx.get()` fails, and stores nothing (a stale entry's background refresh too), unless the loader's `cache()` has a `key()` or its store a `keyGenerator`. Either one switches the check off, so it must itself include the value.
86
+
A loader bound with its own `cache()` is the one loader that doesn't run fresh: its value is stored under the loader, host, path and params. A miss whose body read `cookies()`, `headers()`, `ctx.request.headers` or a non-cacheable `ctx.get()` fails, and stores nothing (a stale entry's background refresh too), unless the loader's `cache()` has a `key()` or its store a `keyGenerator`. Either one switches the check off, so it must itself include the value.
87
87
88
88
Context variables get a third, targeted guard. `createVar({ cache: false })` (or a `ctx.set(var, value, { cache: false })` write — least cacheable wins) taints a value as request-scoped, and a **direct**`ctx.get()` of it inside a `cache()` boundary throws — the guard against serving user A's data to user B. The same read throws inside a `"use cache"` function body, where the value would be stored without being part of the key; pass it in as an argument instead. The guarantee is deliberately narrow: a value _derived_ from a tainted var outside the boundary and cached later is not tracked. Don't read this as "you can't cache user data" — the safe pattern is the natural one: **read tainted context at the point of use, in the path that needs it (a loader or live segment) — never extract user data into a plain value and cache that.**
This is a Flight segment cache: HTML is still rendered on every request. Caching the rendered HTML shell and resuming only the holes is a separate layer, the `ppr` path option ([PPR](/docs/rango/guides/ppr)). Function-level caching uses the `"use cache"` directive ([use cache](/docs/rango/guides/use-cache)), and a loader's data caches with an explicit opt-in (`loader(Fn, () => [cache({ ttl })])`).
50
50
51
-
The guards are correctness-first: `cookies()` and `headers()` throw inside cache scopes rather than silently baking one visitor's data into a shared shell. Read request-scoped data in a loader instead. A loader with its own `cache()` stores its value too, so there a miss fails unless the loader's `cache()` has a `key()`, which must then include it ([Loaders](/docs/rango/features/loaders#live-by-default-even-inside-caches)). [Freshness](/docs/rango/concepts/freshness) covers keys, SWR, nesting, and every guard.
51
+
The guards are correctness-first: `cookies()` and `headers()` throw inside cache scopes rather than silently baking one visitor's data into a shared shell, and so do the raw reads `ctx.request.headers` and `getRequestContext().cookie()` / `.cookies()`. Read request-scoped data in a loader instead. A cache's own `key()`, store `keyGenerator`, `condition()` and `tags()` read the request freely: the value picks or labels the entry, it isn't rendered into it. A loader with its own `cache()` stores its value too, so there a miss fails unless the loader's `cache()` has a `key()`, which must then include it ([Loaders](/docs/rango/features/loaders#live-by-default-even-inside-caches)). [Freshness](/docs/rango/concepts/freshness) covers keys, SWR, nesting, and every guard.
A hit skips the loader body, so the handle pushes it made on the miss (a `Meta` title, `Breadcrumbs`) are stored with the data and replayed on every hit, stale hits included.
64
64
65
-
The entry is keyed by the loader, host, path and params — not by the route's `cache()` key — so one entry serves every user. A body that reads `cookies()`, `headers()` or a `createVar({ cache: false })` variable therefore fails on a miss unless the loader's `cache()` has a `key()`. Any `key()` (or a store `keyGenerator`) switches that check off, so it must include the value:
65
+
The entry is keyed by the loader, host, path and params — not by the route's `cache()` key — so one entry serves every user. A body that reads `cookies()`, `headers()`, `ctx.request.headers` or a `createVar({ cache: false })` variable therefore fails on a miss unless the loader's `cache()` has a `key()`. Any `key()` (or a store `keyGenerator`) switches that check off, so it must include the value:
Every middleware must either call `next()` or return (or throw) a `Response`. Returning or throwing a `Response` short-circuits the chain and becomes the HTTP response; headers and cookies already set are merged into it. `ctx.env` carries your platform bindings; `ctx.set()` shares data with everything downstream.
81
81
82
+
Middleware reads request headers and cookies freely. A handler under `cache()` or on a `ppr` route can't: there `ctx.request.headers`, like `headers()`, throws or refuses the shell capture, since the value would be stored for every visitor. Copy what the handler renders in middleware with `ctx.set()`, and include it in the route's `cache()``key()` so each value gets its own entry ([Freshness](/docs/rango/concepts/freshness)).
83
+
82
84
Cookies and request headers are free functions, not `ctx` members: `cookies().get("session")` and `headers().get("accept-language")`, both imported from `@rangojs/router`. To set a response header, call `ctx.header(name, value)`; after `await next()` it writes to the real downstream response:
Copy file name to clipboardExpand all lines: apps/docs/content/docs/rango/guides/ppr.mdx
+3-3Lines changed: 3 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -282,17 +282,17 @@ The shell is shared per host + URL across all users (per request partition too,
282
282
283
283
What the guards refuse:
284
284
285
-
-`cookies()`, `headers()`, and `ctx.get()` of a `{ cache: false }` variable **throw during the capture render**, wherever the capture waits for them: a handler, a promise it passes or pushes, an async server component, a bake-lane loader, and a loader a handler awaits (`await ctx.use(Loader)`). The capture is refused even if your code catches the throw, and the route keeps serving MISSes with a once-per-key warning. `ctx.dynamic()` called there refuses the capture too. Live-lane loaders (every loader without `ssr: false`) are exempt: they never run at capture.
285
+
-`cookies()`, `headers()`, the raw reads `ctx.request.headers` and `getRequestContext().cookie()` / `.cookies()`, and `ctx.get()` of a `{ cache: false }` variable **throw during the capture render**, wherever the capture waits for them: a handler, a promise it passes or pushes, an async server component, a bake-lane loader, and a loader a handler awaits (`await ctx.use(Loader)`). The capture is refused even if your code catches the throw, and the route keeps serving MISSes with a once-per-key warning. `ctx.dynamic()` called there refuses the capture too. Live-lane loaders (every loader without `ssr: false`) are exempt: they never run at capture.
286
286
-`ctx.theme` and `getRequestContext().theme` are the visitor's theme cookie, so reading either anywhere the capture waits for refuses it the same way (warned once per key) and the route keeps serving MISSes. Read the theme with `useTheme()` in a client component, or in a live loader with `cookies().get("theme")`. The shell carries the no-cookie default theme, whoever captured it: a `useTheme()` reader shows the default to a visitor with no stored theme, and switches to a stored theme after hydration. The `<html>` theme class is right before paint either way.
287
-
- The guard sees only those reads. A handler or bake-lane loader reading a normal middleware-provided session object (`ctx.get("session")`), or raw request headers, refuses nothing — whatever it renders or returns as plain data is photographed as the capturing user's state. `return { user: session.user }` bakes that user into the shared shell for every visitor. Creating the variable with `createVar({ cache: false })` turns such a read into a refusal instead.
287
+
- The guard sees only those reads. A handler or bake-lane loader reading a normal middleware-provided session object (`ctx.get("session")`) refuses nothing — whatever it renders or returns as plain data is photographed as the capturing user's state. `return { user: session.user }` bakes that user into the shared shell for every visitor. Creating the variable with `createVar({ cache: false })` turns such a read into a refusal instead.
288
288
- Inside a bake-lane loader, nested promises are the escape hatch for such data, and they hold regardless of timing: the capture masks every promise nested in a bake-lane container (even an already-resolved `Promise.resolve(null)`), so the consumer's `<Suspense>` becomes a hole that streams the fresh value on every HIT. They are not an escape for `cookies()`/`headers()`: the promise body still runs during capture and trips the guard. A promise in handler output is no escape at all — it bakes.
289
289
- Rule of thumb: per-user data on a PPR page lives in a live-lane loader (no `ssr: false`) consumed client-side with `useLoader` under `loading()` or an inline `<Suspense>`, or in a nested promise in bake-lane loader data.
290
290
291
291
## Pitfalls
292
292
293
293
-**Handler and loader header writes throw.** On a `ppr` route only middleware writes response headers. A handler or loader calling `ctx.headers.set()`, `cookies().set()`, `ctx.setTheme()`, or the request-context `header()`/`setStatus()` throws on every render: handlers never run on HITs (their output is replayed, so the write would differ between MISS and HIT), and loaders settle after the shell's headers have flushed. Move the write into route middleware, which runs on every request including HITs. The one exception: a handler that calls `ctx.dynamic()` first may write its own headers, because that render never HITs.
294
294
-**A pending handler promise expected to be a hole** — it is not. A promise the handler passes under `<Suspense>`, an async server component, or a promise nested in a handler's handle push is awaited at capture and served frozen on every HIT. Move per-request data into a live-lane loader read with `useLoader` under `loading()` or an inline `<Suspense>`.
295
-
-**A request-scoped read the capture waits for** (`cookies()`, `headers()`, a `{ cache: false }` variable, `ctx.dynamic()`) — the capture is refused (warned once per key) and the route keeps serving MISSes. Move the read onto the live lane: a loader without `ssr: false`, read under `loading()` or an inline `<Suspense>`.
295
+
-**A request-scoped read the capture waits for** (`cookies()`, `headers()`, `ctx.request.headers`, a `{ cache: false }` variable, `ctx.dynamic()`) — the capture is refused (warned once per key) and the route keeps serving MISSes. Move the read onto the live lane: a loader without `ssr: false`, read under `loading()` or an inline `<Suspense>`.
296
296
-**A loader a handler awaits (`await ctx.use(Loader)`) that reads `cookies()` or `headers()`** — refuses the capture like any other read the capture waits for: every request is `x-rango-shell: MISS`, and the warning names the loader. Register the loader with `loading()` and read it with `useLoader` instead. On a route without `ppr`, `cache()` still allows it.
297
297
-**A bake-lane container that must be fresh per document GET** — it is snapshot-pinned for the shell's lifetime by design. Use the live lane (drop `ssr: false`) or a nested promise.
298
298
-**Handler output or a bake-lane loader slower than `ppr.captureTimeout` (15s by default)** — the capture stores nothing rather than a partial shell. Make the slow part cheaper with `cache()`/`"use cache"`, move it into a live loader, or raise the budget.
|`cookies()`, `headers()`| Throws | Per-request values aren't in the cache key — one user's data would serve another |
107
+
|`ctx.request.headers` (any `ctx` passed in), `getRequestContext().cookie()` / `.cookies()`| Throws | Same reason: a `ctx` or `Request` argument is keyed by its route and URL only |
107
108
|`ctx.set()`, `ctx.headers.set()` (and the other mutating `Headers` methods), `ctx.setTheme()`, `ctx.setLocationState()`| Throws | Effects are lost on a hit (the body is skipped) |
const data =awaitgetCachedData(locale); // locale is now in the cache key
120
+
121
+
// the same for a header read from ctx.request
122
+
const language =ctx.request.headers.get("accept-language") ??"en";
123
+
const greeting =awaitgetGreeting(language);
119
124
```
120
125
126
+
A `ctx` or `Request` argument keys the entry by its route and URL only. `ctx.request.clone()` is guarded like `ctx.request.headers`. `fetch(ctx.request)` and `new Request(ctx.request)` don't throw, but the guard can't see through them: a fetch forwards the visitor's `Cookie` and `Authorization`, so its response is per visitor, and the copy's headers are the visitor's. Don't make either inside a cached body; fetch outside it, or pass the values the fetch depends on in as arguments.
127
+
121
128
And keep ctx side effects outside the cached function:
0 commit comments