Skip to content

Commit 36e21af

Browse files
authored
fix(router): ctx.theme read in a handler refuses a PPR capture and throws in a cache() miss, like cookies() (#971) (#979)
The visitor's theme was a plain read in three places: the handler ctx (copied at creation), the middleware ctx and getRequestContext().theme. A ppr shell, a route cache() entry or a "use cache" entry stored the first visitor's theme and served it to every later visitor. Each read is now a read-only, non-enumerable getter that runs the cookies() guards (same scopes, order and exemptions): a ppr capture refuses with a once-per-key warning and the route keeps MISSing, and a cache() or "use cache" read throws. The guard records the read and its fix, so the refusal warning prints both. The router's own payload read goes through payloadInitialTheme, unguarded, and a capture stores the no-cookie default as the shell's initialTheme instead of the capturing visitor's theme, so a HIT no longer hands one visitor's useTheme() value to a visitor with no stored theme.
1 parent 25029fb commit 36e21af

44 files changed

Lines changed: 1597 additions & 111 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/docs/content/docs/rango/concepts/freshness.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,8 @@ That loader exemption is also the default contract of `cache()`: cached UI plus
7878

7979
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:
8080

81-
- **`cache()` boundary guard** — fires while the handler runs on a miss. `cookies()` and `headers()` 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-
- **`"use cache"` exec guard** — the same request-scoped APIs 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.
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.
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.
8383

8484
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.
8585

‎apps/docs/content/docs/rango/guides/ppr.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@ The shell is shared per host + URL across all users (per request partition too,
281281
What the guards refuse:
282282

283283
- `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.
284+
- `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.
284285
- 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.
285286
- 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.
286287
- 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.

‎apps/docs/content/docs/rango/guides/theme.mdx‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -121,12 +121,14 @@ export function ThemeToggle() {
121121

122122
## Read and set it on the server
123123

124-
Handlers and middleware get `ctx.theme` and `ctx.setTheme()`. `ctx.theme` is the stored theme, or `defaultTheme` when there is none. `ctx.setTheme(theme)` sets the theme cookie on the response; invalid values are rejected with a console warning. Both are typed optional because they exist only when `theme` is configured, so call the setter as `ctx.setTheme?.()`:
124+
Handlers and middleware get `ctx.theme` and `ctx.setTheme()`, and any server code can read `getRequestContext().theme`. `ctx.theme` is the stored theme, or `defaultTheme` when there is none. `ctx.setTheme(theme)` sets the theme cookie on the response; invalid values are rejected with a console warning. Both are typed optional because they exist only when `theme` is configured, so call the setter as `ctx.setTheme?.()`.
125+
126+
The theme is the visitor's cookie, so a handler reads it only on a route whose output is rendered per request (see [On `ppr` and `cache()` routes](#on-ppr-and-cache-routes)):
125127

126128
```tsx
127129
import type { Middleware } from "@rangojs/router";
128130

129-
// In a handler
131+
// In a handler on a route without ppr or cache()
130132
path("/settings", (ctx) => {
131133
const currentTheme = ctx.theme; // "light" | "dark" | "system" | undefined
132134
return <SettingsPage theme={currentTheme} />;
@@ -144,7 +146,29 @@ export const themeFromQuery: Middleware = async (ctx, next) => {
144146

145147
Setting the theme in [middleware](/docs/rango/features/middleware) is also the right spot when the preference lives in your user record rather than the browser.
146148

147-
Loaders do not get `ctx.theme` or `ctx.setTheme`. A loader that needs the theme reads the cookie directly (loaders run fresh on every request, so the read is safe):
149+
### On `ppr` and `cache()` routes
150+
151+
A [`ppr`](/docs/rango/guides/ppr) shell and a `cache()` entry are shared by every visitor, so a handler there must not read the visitor's theme. `ctx.theme` (handler and middleware) and `getRequestContext().theme` are guarded like `cookies()`:
152+
153+
| Where the theme is read | What happens |
154+
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
155+
| a handler on a `ppr` route | The shell capture is refused (warned once per URL); every request stays a MISS |
156+
| inside a `cache()` boundary | Throws on a cache miss, like `cookies()` |
157+
| inside a `"use cache"` function (handler or middleware) | Throws; read it outside and pass it in as an argument |
158+
| after `ctx.dynamic()` on `ppr` | Allowed: that render is never captured |
159+
| middleware `ctx.set()` of the theme, read by a handler | Not guarded: the first visitor's theme bakes into the shell or `cache()` entry, like a session object |
160+
| a route with no `ppr` or `cache()` above it, or middleware | Allowed: rendered per request |
161+
162+
The theme getters are read-only and non-enumerable: `{ ...ctx }` and `Object.assign({}, ctx)` do not carry `theme`, and assigning it throws. `ctx.setTheme()` throws in a handler on these routes too, like any response write there; call it from middleware.
163+
164+
Read the theme where it is per request instead:
165+
166+
- `useTheme()` in a client component. The `<html>` class is right before paint (the theme script sets it). On a `ppr` HIT the shell carries the no-cookie default (`defaultTheme`), whoever captured it: a visitor with no stored theme sees the default, and one with a stored theme sees it after hydration.
167+
- A live loader (no `ssr: false`), below.
168+
169+
### In a loader
170+
171+
Loaders do not get `ctx.theme` or `ctx.setTheme`. A loader that needs the theme reads the cookie directly. A live loader runs on every request, `ppr` HITs included, and on a `ppr` route needs `loading()` or an inline `<Suspense>` above its reader. A bake-lane loader (`ssr: false`) runs at capture, where this `cookies()` read refuses the capture:
148172

149173
```ts
150174
import { cookies, createLoader } from "@rangojs/router";
@@ -157,9 +181,11 @@ export const ThemedLoader = createLoader(async () => {
157181

158182
## Pitfalls
159183

160-
| Symptom | Fix |
161-
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
162-
| Page flashes the wrong theme on load | Render `<Html.Meta />` (or `<ThemeScript />`) in the document head — it carries the FOUC-prevention script |
163-
| React hydration warning on the `<html>` element | Add `suppressHydrationWarning` to `<html>` |
164-
| No `ctx.theme` in a loader | Loaders don't get it; read the cookie with `cookies().get(storageKey)` |
165-
| Tailwind `dark:` follows the OS, not the toggle | Add `@custom-variant dark` to your CSS so the variant reads the class (see [Tailwind](/docs/rango/guides/tailwind)) |
184+
| Symptom | Fix |
185+
| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
186+
| Page flashes the wrong theme on load | Render `<Html.Meta />` (or `<ThemeScript />`) in the document head — it carries the FOUC-prevention script |
187+
| React hydration warning on the `<html>` element | Add `suppressHydrationWarning` to `<html>` |
188+
| No `ctx.theme` in a loader | Loaders don't get it; read the cookie with `cookies().get(storageKey)` |
189+
| A `cache()` route that reads `ctx.theme` answers 500 | The read throws inside a `cache()` boundary, like `cookies()`; read the theme with `useTheme()` or in a loader |
190+
| A `ppr` route that reads `ctx.theme` never HITs | The capture is refused (a once-per-URL `Shell capture ... was refused` warning names the read); read the theme with `useTheme()` or in a live loader |
191+
| Tailwind `dark:` follows the OS, not the toggle | Add `@custom-variant dark` to your CSS so the variant reads the class (see [Tailwind](/docs/rango/guides/tailwind)) |

‎apps/docs/src/content.gen.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1924,8 +1924,13 @@ export const pageMeta: PageMeta[] = [
19241924
},
19251925
{
19261926
"depth": 3,
1927-
"id": "promise-holes-no-loader-required",
1928-
"text": "Promise holes: no loader required"
1927+
"id": "handler-output-always-bakes",
1928+
"text": "Handler output always bakes"
1929+
},
1930+
{
1931+
"depth": 3,
1932+
"id": "migrating-from-the-old-promise-hole-model",
1933+
"text": "Migrating from the old promise-hole model"
19291934
},
19301935
{
19311936
"depth": 3,
@@ -2457,6 +2462,16 @@ export const pageMeta: PageMeta[] = [
24572462
"id": "read-and-set-it-on-the-server",
24582463
"text": "Read and set it on the server"
24592464
},
2465+
{
2466+
"depth": 3,
2467+
"id": "on-ppr-and-cache-routes",
2468+
"text": "On ppr and cache() routes"
2469+
},
2470+
{
2471+
"depth": 3,
2472+
"id": "in-a-loader",
2473+
"text": "In a loader"
2474+
},
24602475
{
24612476
"depth": 2,
24622477
"id": "pitfalls",

‎packages/rangojs-router/CHANGELOG.md‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,61 @@ raw request input from `key()` (prefix, normalize or encode it), or a value
6565
containing `|` can name another partition's record
6666
([#975](https://github.com/rangojs/rango/issues/975)).
6767

68+
### Breaking: reading the visitor's theme on a `ppr` or `cache()` route refuses the capture or throws, like `cookies()` ([#979](https://github.com/rangojs/rango/pull/979))
69+
70+
`ctx.theme` in a handler, `ctx.theme` in middleware and
71+
`getRequestContext().theme` are the visitor's theme cookie, but they were
72+
plain reads. A `ppr` shell, a route `cache()` entry or a `"use cache"` entry
73+
stored the first visitor's theme and served it to every later visitor until
74+
the entry expired (#971). The shell also stored the capturing visitor's theme
75+
as its `initialTheme`, so on a HIT a visitor with no stored theme kept that
76+
visitor's `useTheme().theme` for the life of the page.
77+
78+
The reads are now guarded like `cookies()`, with the same exemptions:
79+
80+
- On a `ppr` route, a handler that reads the theme has its shell capture
81+
refused (warned once per URL). Every request stays an
82+
`x-rango-shell: MISS` rendered with that visitor's theme.
83+
- Inside a `cache()` boundary or a `"use cache"` function the read throws. A
84+
`cache()` route that reads it answers 500 where it used to answer 200.
85+
- The shell's `initialTheme` is the no-cookie default (`defaultTheme`),
86+
whoever captured it. A visitor with a stored theme gets it pre-paint from
87+
the theme script and in `useTheme()` after hydration.
88+
- The theme getters are read-only and non-enumerable. `{ ...ctx }` and
89+
`Object.assign({}, ctx)` no longer carry `theme`, and `ctx.theme = x` throws
90+
(it is typed `readonly`). Read `ctx.theme` directly.
91+
- A fetchable loader's ctx is a spread of the request context, so an untyped
92+
JS fetchable loader no longer sees `ctx.theme` at runtime (`LoaderContext`
93+
never typed it). Read `getRequestContext().theme` or the cookie instead.
94+
- `ctx.theme` is read when it is accessed, so after `ctx.setTheme()` in the
95+
same request it returns the new theme, as the middleware ctx already did.
96+
97+
Read the theme where it is per request: `useTheme()` in a client component,
98+
or a live loader (no `ssr: false`).
99+
100+
```tsx
101+
// Before: the first visitor's theme was stored in the shell and served to all.
102+
path("/settings", (ctx) => <SettingsPage theme={ctx.theme} />, { ppr: true });
103+
104+
// After: the page reads the theme on the client.
105+
path("/settings", () => <SettingsPage />, { ppr: true });
106+
```
107+
108+
```tsx
109+
// settings-page.tsx
110+
"use client";
111+
import { useTheme } from "@rangojs/router/theme";
112+
113+
export function SettingsPage() {
114+
const { theme } = useTheme();
115+
return <p>{`theme: ${theme}`}</p>;
116+
}
117+
```
118+
119+
A server-side read moves into a live loader, read under `loading()`:
120+
`createLoader(async () => cookies().get("theme")?.value ?? "system")` (the
121+
cookie name is `storageKey`).
122+
68123
### Breaking: a route `cache()` entry is tagged by what its content recorded, so `updateTag()` evicts shells and documents built from it ([#965](https://github.com/rangojs/rango/pull/965))
69124

70125
On a `ppr` route with its own `cache()`, the shell capture replays the route's

‎packages/rangojs-router/docs/internal/execution-model.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,8 +223,10 @@ global middleware
223223
for all of it before it freezes anything (`settleCaptureRecord` in
224224
`src/rsc/shell-capture.ts`), bounded by the one `ppr.captureTimeout`
225225
deadline; output that does not settle in time stores no shell. The capture
226-
guard (`assertNotInsideShellCapture` in `src/server/context.ts`: `cookies()`,
227-
`headers()`, a `{ cache: false }` variable read) covers everything the
226+
guard (`assertNotInsideShellCapture` / `tripShellCaptureGuard` in
227+
`src/server/context.ts`: `cookies()`, `headers()`, a `{ cache: false }`
228+
variable read, and the theme reads `ctx.theme` / `getRequestContext().theme`
229+
through `assertThemeReadAllowed`, #971) covers everything the
228230
capture waits for — handler and render code, bake-lane segment loaders, and
229231
handler-invoked loader bodies (no exemption on this tier; the
230232
consumption-lane rule below). `ctx.dynamic()` called anywhere the capture

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,8 @@ Internal: the rango state lives in a session cookie (`src/browser/rango-state.ts
555555

556556
Router option `theme`, `ThemeProvider` integration on server and client, `ThemeScript` generation, FOUC prevention, cookie-based persistence.
557557

558+
The visitor's theme reads (the handler and middleware `ctx.theme`, `getRequestContext().theme`) are read-only, non-enumerable getters guarded like `cookies()` (#971, `assertThemeReadAllowed` in `server/cookie-store.ts`; getters in `router/handler-context.ts` `THEME_DESCRIPTOR`, `router/middleware.ts` `MIDDLEWARE_THEME_DESCRIPTOR`, `server/request-context.ts`). Non-enumerable so dev Flight's debug serialization of a ctx passed as a server component prop is not a read. A read refuses a `ppr` shell capture (the guard records `_shellCaptureGuardTripped = { surface, fix }` and the once-per-key refusal warning prints both; `cookies()`/`headers()` record theirs the same way), and throws inside a `cache()` boundary or a `"use cache"` body, with the same loader-body exemptions as `cookies()`. The router's own read is `payloadInitialTheme` (`rsc/full-payload.ts`, over the unguarded internal `_readTheme()`, itself non-enumerable so the fetchable-loader ctx's `{ ...reqCtx }` spread in `rsc/loader-fetch.ts` cannot carry it), used for `metadata.initialTheme` by the full, 404 and PE payloads and for `ShellCacheEntry.initialTheme`: a capture carries the no-cookie `defaultTheme`, so a HIT never hands one visitor's theme to `useTheme()` for another. `ctx.setTheme()` is a response write, refused on `ppr`/`cache()` routes by the #713 header guard.
559+
558560
### Prerender and Build-time Pre-rendering
559561

560562
- `Prerender()`/`Static()` handler types, `BuildContext`, `GetParamsContext`.

‎packages/rangojs-router/e2e/test-app/src/router.named-routes.gen.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,9 @@ export const NamedRoutes = {
445445
testPrerenderManifestEntries: "/__test/prerender-manifest-entries",
446446
testThrowHandlerError: "/__test/throw-handler-error",
447447
"theme.index": "/theme",
448+
"theme.ppr": "/theme/ppr",
449+
"theme.pprClient": "/theme/ppr-client",
450+
"theme.pprRc": "/theme/ppr-rc",
448451
"theme.toggle": "/theme/toggle",
449452
"trailingSlash.always": "/ts-always",
450453
"trailingSlash.ignore": "/ts-ignore",

‎packages/rangojs-router/e2e/test-app/src/urls.gen.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,9 @@ export const routes = {
321321
testPrerenderManifestEntries: "/__test/prerender-manifest-entries",
322322
testThrowHandlerError: "/__test/throw-handler-error",
323323
"theme.index": "/theme",
324+
"theme.ppr": "/theme/ppr",
325+
"theme.pprClient": "/theme/ppr-client",
326+
"theme.pprRc": "/theme/ppr-rc",
324327
"theme.toggle": "/theme/toggle",
325328
"trailingSlash.always": "/ts-always",
326329
"trailingSlash.ignore": "/ts-ignore",
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Auto-generated by @rangojs/router - do not edit
22
export const routes = {
33
index: "/",
4+
ppr: "/ppr",
5+
pprClient: "/ppr-client",
6+
pprRc: "/ppr-rc",
47
toggle: "/toggle",
58
} as const;
69
export type routes = typeof routes;

0 commit comments

Comments
 (0)