Skip to content

Commit 4d0e587

Browse files
committed
fix(router): fail or skip a prerendered route whose component throws while the build encodes it
Prerender baked a Flight error row when the handler returned but a component in its tree threw during the build-time encode (an async server component whose fetch failed): the build logged OK and the route served its error boundary until the next build. #587's policy only saw handler throws, because Flight reports a component throw through onError and completes normally. matchForPrerender and renderStaticSegment now pass onError to every encode and re-throw the first error, so prerender.onError decides exactly as for a handler throw. serializeResult, encodeHandles and encodeHandleValue gain the optional trailing onError. Closes #914
1 parent a6a8a26 commit 4d0e587

13 files changed

Lines changed: 428 additions & 17 deletions

File tree

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,11 +259,14 @@ A handler that throws a non-`Skip` error is surfaced to the build — never bake
259259
| `return ctx.passthrough()` | No entry, logged `PASS` | No entry, `PASS` |
260260
| `throw new Skip("reason")` | No entry, logged `SKIP`, build goes on | No entry, `SKIP`, build goes on |
261261
| `throw new Error("reason")` | Logged `FAIL`, the build stops | Logged `WARN`, URL left un-baked |
262+
| A child component throws | Logged `FAIL`, the build stops | Logged `WARN`, URL left un-baked |
262263

263264
```ts
264265
rango({ prerender: { onError: "warn" } });
265266
```
266267

268+
The last row is a handler that returns fine while an async server component in its tree throws during the build-time render, for example because its fetch fails. It goes through the same policy instead of being baked as an error, and a `Skip` thrown there skips the URL.
269+
267270
`"warn"` is a build-unblock, not a runtime contract: the un-baked route falls through to normal resolution and may render live or 404 depending on the rest of the build. For defined runtime behavior use `Passthrough()` or `throw new Skip()`; otherwise keep the default. Both `Skip` and hard errors also reach the router's `onError` callback with phase `"prerender"` or `"static"`.
268271

269272
## Build output

‎docs/design/caching.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,8 @@ Key points:
121121
- Revival produces a React element identical to the original
122122
- Cached elements render correctly in both RSC stream and HTML output
123123
- A component that is still a promise (a route, parallel slot or intercept handler streamed under `loading()`) is awaited before encoding (`serializeSegments` in `src/cache/segment-codec.ts`); if it rejects, the serialize step throws and `cacheRoute` writes nothing, so a handler that fails after the 200 has gone out, which the MISS gate's `response.status !== 200` check in `withCacheStore` cannot see, never replaces an entry
124-
- A component that throws while a segment is encoded (an async server component in a handler's tree) does not reject the encode: Flight reports it through `onError` and completes normally with an error row (`1:E{"digest":""}`) that throws wherever the decoded tree renders. `cacheRoute` passes an `onError` to `serializeSegments` (`src/cache/segment-codec.ts`) and, if it fires, writes nothing and reports the error as `cache-write`, so the next request is a MISS and a stale entry keeps serving. The encode re-runs the tree, so only a throw during the encode blocks the write. Prerender calls `serializeSegments` without `onError` and still stores the error row
125-
- The item writers and handle values follow the same rule. Besides an async component that throws, Flight reports a rejected promise, a function, a class instance and a local symbol through `onError` and writes an error row, so `serializeResult`'s `null` never fires for them. `serializeResult` (`src/cache/segment-codec.ts`) and `encodeHandles` / `encodeHandleValue` (`src/cache/handle-snapshot.ts`) take the same optional `onError`, and each writer passes one collector to its value encode and its handle encode: `"use cache"` (`src/cache/cache-runtime.ts`, the miss leader and the stale-hit refresh), a loader's own `cache()` (`src/router/segment-resolution/loader-cache.ts`, whose `setItem` throws into `readThroughItem`'s report) and `cacheRoute`. If it fires, nothing is written and the error is reported as `cache-write` (miss) or `stale-revalidation` (background refresh), so the next call re-runs and a stale entry keeps serving. A handle value that fails to encode refuses the whole entry rather than dropping only the handle blob: a hit replays the blob in place of the body's pushes, so an entry without it would serve a page missing its title or breadcrumbs until expiry. The blob is still dropped, entry kept, when its encode passes the 5 s `HANDLE_ENCODE_TIMEOUT_MS`. Prerender calls both without `onError` and still stores the error row
124+
- A component that throws while a segment is encoded (an async server component in a handler's tree) does not reject the encode: Flight reports it through `onError` and completes normally with an error row (`1:E{"digest":""}`) that throws wherever the decoded tree renders. `cacheRoute` passes an `onError` to `serializeSegments` (`src/cache/segment-codec.ts`) and, if it fires, writes nothing and reports the error as `cache-write`, so the next request is a MISS and a stale entry keeps serving. The encode re-runs the tree, so only a throw during the encode blocks the write. Prerender passes an `onError` the same way and hands the first error to the build's `prerender.onError` policy (see Render Errors in `packages/rangojs-router/docs/prerender-api-design.md`)
125+
- The item writers and handle values follow the same rule. Besides an async component that throws, Flight reports a rejected promise, a function, a class instance and a local symbol through `onError` and writes an error row, so `serializeResult`'s `null` never fires for them. `serializeResult` (`src/cache/segment-codec.ts`) and `encodeHandles` / `encodeHandleValue` (`src/cache/handle-snapshot.ts`) take the same optional `onError`, and each writer passes one collector to its value encode and its handle encode: `"use cache"` (`src/cache/cache-runtime.ts`, the miss leader and the stale-hit refresh), a loader's own `cache()` (`src/router/segment-resolution/loader-cache.ts`, whose `setItem` throws into `readThroughItem`'s report) and `cacheRoute`. If it fires, nothing is written and the error is reported as `cache-write` (miss) or `stale-revalidation` (background refresh), so the next call re-runs and a stale entry keeps serving. A handle value that fails to encode refuses the whole entry rather than dropping only the handle blob: a hit replays the blob in place of the body's pushes, so an entry without it would serve a page missing its title or breadcrumbs until expiry. The blob is still dropped, entry kept, when its encode passes the 5 s `HANDLE_ENCODE_TIMEOUT_MS`. Prerender passes the same collector and hands the first error to its `prerender.onError` policy
126126

127127
## API
128128

‎packages/rangojs-router/CHANGELOG.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,28 @@ these are now checked against it, as middleware reverse already was. Without
6464
a generated map, any name except a dot-prefixed literal is accepted. Runtime
6565
behavior is unchanged. Pass the fully qualified name and every param.
6666

67+
### Breaking: a component that throws while a route is prerendered fails the build ([#917](https://github.com/rangojs/rango/pull/917))
68+
69+
A `Prerender()` route or `Static()` handler could return normally while its
70+
tree held a component that threw during the build-time render, such as an
71+
async server component whose fetch failed. Flight encoded that component as an
72+
error row, the build logged `OK`, and the route served its error boundary
73+
until the next build. The error now takes the same path as a handler throw:
74+
75+
- `prerender.onError: "fail"` (the default) fails the build and names the URL
76+
and the error.
77+
- `"warn"` logs `WARN` and skips the URL.
78+
- A `Skip` thrown by the component skips the URL.
79+
- The router's `onError` receives it with phase `"prerender"` or `"static"`.
80+
81+
Intercept variants and handle values are checked the same way. In dev, the
82+
`/__rsc_prerender` endpoint falls through to a live render for such a route
83+
instead of serving a payload that holds the error row.
84+
85+
Migration: a build that passed with such a route now fails. Fix the component,
86+
`throw new Skip()` for URLs that cannot render at build time, or set
87+
`rango({ prerender: { onError: "warn" } })` to skip them.
88+
6789
### Added: `router.debugManifest()` on the public `Rango` type ([#874](https://github.com/rangojs/rango/pull/874))
6890

6991
`debugManifest()` was typed only on the internal router interface, so calling

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,9 @@ Router option `theme`, `ThemeProvider` integration on server and client, `ThemeS
551551
keys; `x-rango-prerender-cache: HIT | MISS` response header
552552
- Build-time render errors surface to the build instead of baking an error page
553553
(issue #587): `ResolveSegmentOptions.throwOnError` (set only by the prerender
554-
path) re-throws through `matchForPrerender`. `prerender.onError` Vite plugin
554+
path) re-throws through `matchForPrerender`; a component that throws while
555+
the tree is encoded is collected through Flight `onError` and re-thrown the
556+
same way (issue #914). `prerender.onError` Vite plugin
555557
option (`"fail"` default | `"warn"`) chooses fail-the-build vs. warn-and-skip;
556558
`throw new Skip()` inside a render fn skips a single URL/handler
557559

‎packages/rangojs-router/docs/prerender-api-design.md‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ route was pre-rendered.
3030
- **Dev mode** - On-demand rendering via `/__rsc_prerender` endpoint
3131
- **Intercept pre-rendering** - Intercept variants stored under `/i` key
3232
- **Render-error handling** - a build-time render throw surfaces to the build (fail
33-
by default, or `prerender.onError: "warn"` to skip the URL); `throw new Skip()`
34-
in a render fn skips one URL. See [Render Errors](#render-errors).
33+
by default, or `prerender.onError: "warn"` to skip the URL), including a
34+
component that throws while the tree is encoded; `throw new Skip()` in a render
35+
fn skips one URL. See [Render Errors](#render-errors).
3536
- **Build-time PPR shells (producer B, #699)** - a `Prerender` route that also
3637
declares the `ppr` path option gets its complete PPR shell entry (HTML prelude +
3738
postponed state) produced at `vite build` and served from the very first
@@ -294,11 +295,24 @@ instead of converted into an error segment, so it reaches the build loop
294295
(`expandPrerenderRoutes`). The live request path leaves the flag unset, so runtime
295296
error boundaries are unchanged.
296297

298+
`throwOnError` only sees what the handler itself throws. A component in the tree
299+
it returns can still throw later, while the tree is encoded: say an async server
300+
component whose fetch fails at build. Flight doesn't reject there. It reports the
301+
error through `onError` and finishes normally, writing an error row
302+
(`1:E{"digest":""}`) that throws wherever the decoded tree renders. Until #914 the
303+
build logged `OK` for that too, and the route served its error boundary until the
304+
next build. So `matchForPrerender` and `renderStaticSegment` pass an `onError` to
305+
every encode (segments, intercept segments, handles) and re-throw the first error
306+
collected. A main-route error is thrown before any intercept handler runs, as a
307+
handler throw would be. From there it takes the handler-throw path: the policy
308+
below applies, and a `Skip` thrown by such a component skips the URL.
309+
297310
What the build then does is `prerender.onError` (a rango() plugin option):
298311

299312
| build handler outcome | `"fail"` (default) | `"warn"` |
300313
| --------------------------------- | --------------------------------------- | ------------------------- |
301314
| render throws | build fails, names the URL + the error | warn, skip baking the URL |
315+
| a component throws while encoding | build fails, names the URL + the error | warn, skip baking the URL |
302316
| `throw new Skip()` in the render | URL skipped (logged `SKIP`) | URL skipped |
303317
| `ctx.passthrough()` (Passthrough) | defer to the live handler (no artifact) | defer to the live handler |
304318

‎packages/rangojs-router/e2e/prerender-onerror.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ import { x } from "tinyexec";
2323
* - prerender.onError "warn": the build SUCCEEDS and the entry is skipped (not baked);
2424
* - both Prerender routes and Static() handlers go through the same policy.
2525
*
26+
* #914 adds PrerenderChildBoom (RANGO_TEST_PRERENDER_CHILD_ERROR): its handler
27+
* returns normally and an async child throws while the build encodes the tree, so
28+
* the throw reaches the build through Flight onError rather than the handler. It
29+
* must take the same policy path.
30+
*
2631
* Build-only by design (explicit gap): #587 is a build-time bug and prerender.onError
2732
* is build config. The dev `/__rsc_prerender` endpoint tweak (router-discovery.ts) is
2833
* a cosmetic log refinement (stay quiet on Skip) on a path that serves ONLY non-Node
@@ -77,6 +82,45 @@ test.describe("prerender render error (production)", () => {
7782
expect(out).toContain("Pre-render complete: 0 done, 1 skipped");
7883
});
7984

85+
test("an async child that throws while the route is encoded fails the build by default", async () => {
86+
const res = await x("pnpm", ["build"], {
87+
nodeOptions: {
88+
cwd,
89+
env: buildEnv({ RANGO_TEST_PRERENDER_CHILD_ERROR: "1" }),
90+
},
91+
throwOnError: false,
92+
});
93+
const out = `${res.stdout}\n${res.stderr}`;
94+
expect(
95+
res.exitCode,
96+
`build should exit non-zero; output:\n${out}`,
97+
).not.toBe(0);
98+
expect(out).toContain("async child build-time render failure");
99+
expect(out).toMatch(/FAIL\s+\/prerender-child-boom/);
100+
});
101+
102+
test('an async child that throws under prerender.onError "warn" is skipped, not baked', async () => {
103+
const res = await x("pnpm", ["build"], {
104+
nodeOptions: {
105+
cwd,
106+
env: buildEnv({
107+
RANGO_TEST_PRERENDER_CHILD_ERROR: "1",
108+
RANGO_TEST_PRERENDER_ONERROR: "warn",
109+
}),
110+
},
111+
throwOnError: false,
112+
});
113+
const out = `${res.stdout}\n${res.stderr}`;
114+
expect(
115+
res.exitCode,
116+
`warn build should succeed (exit 0); output:\n${out}`,
117+
).toBe(0);
118+
expect(out).toMatch(
119+
/WARN\s+\/prerender-child-boom.*prerender\.onError: "warn"/,
120+
);
121+
expect(out).toContain("Pre-render complete: 0 done, 1 skipped");
122+
});
123+
80124
test("a Static() handler render error also fails the build by default", async () => {
81125
// No prerender error this run, so the prerender phase succeeds and the build
82126
// reaches renderStaticHandlers, where StaticBoom throws and the same

‎packages/rangojs-router/e2e/prerender-onerror/src/router.tsx‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,21 @@ export const PrerenderBoom = Prerender(async (ctx) => {
1212
return <div data-testid="prerender-boom">{region}</div>;
1313
});
1414

15+
// A Prerender route whose handler returns normally but whose tree holds an async
16+
// component that throws while the build encodes it (#914). Flight reports that
17+
// through onError instead of rejecting, so only the encode sees the throw.
18+
// Registered only when RANGO_TEST_PRERENDER_CHILD_ERROR is set.
19+
async function ChildBoom(): Promise<never> {
20+
await Promise.resolve();
21+
throw new Error("async child build-time render failure (#914 fixture)");
22+
}
23+
24+
export const PrerenderChildBoom = Prerender(async () => (
25+
<div data-testid="prerender-child-boom">
26+
<ChildBoom />
27+
</div>
28+
));
29+
1530
// A Static handler exercising the SAME prerender.onError policy via the
1631
// renderStaticHandlers loop. Static handlers are discovered by export (not route
1732
// registration), so it throws ONLY when RANGO_TEST_STATIC_ERROR is set and renders
@@ -36,4 +51,7 @@ export const router = createRouter({}).routes(({ path }) => [
3651
...(process.env.RANGO_TEST_PRERENDER_ERROR
3752
? [path("/prerender-boom", PrerenderBoom)]
3853
: []),
54+
...(process.env.RANGO_TEST_PRERENDER_CHILD_ERROR
55+
? [path("/prerender-child-boom", PrerenderChildBoom)]
56+
: []),
3957
]);

‎packages/rangojs-router/skills/prerender/SKILL.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,12 @@ rango({ prerender: { onError: "warn" } }); // default is "fail"
495495
| `return ctx.passthrough()` | Skip entry, log PASS (Passthrough routes) | Skip entry, log PASS |
496496
| `throw new Skip("reason")` | Skip entry, log SKIP, continue | Skip entry, log SKIP, continue |
497497
| `throw new Error("reason")` | Log FAIL, stop ALL pre-rendering, fail build | Log WARN, skip the URL, continue |
498+
| A child component throws | Log FAIL, stop ALL pre-rendering, fail build | Log WARN, skip the URL, continue |
499+
500+
The last row covers a handler that returns fine but whose tree holds an async
501+
server component that throws while the page is rendered at build, for example
502+
because its fetch fails. That error goes through the same policy instead of being
503+
baked as an error row, and a `Skip` thrown there skips the URL.
498504

499505
With `"warn"` the errored entry is logged and left un-baked (never served as a baked
500506
200 error page). `"warn"` is a build-unblock, not a runtime contract: the route falls

‎packages/rangojs-router/src/cache/__tests__/cache-route-flight-error.rsc-test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ describe("serializeSegments onError (real Flight)", () => {
188188
]);
189189
});
190190

191-
it("without onError (prerender) still encodes the error row and resolves", async () => {
191+
it("without onError still encodes the error row and resolves", async () => {
192192
failReviews = true;
193193
const [serialized] = await serializeSegments([segment]);
194194
expect(errorRows([serialized])).toEqual(['1:E{"digest":""}']);

‎packages/rangojs-router/src/cache/handle-snapshot.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ function withTimeout<T>(p: Promise<T>, ms: number, onTimeout: T): Promise<T> {
5151
* `onError` reaches the Flight encode (see serializeResult). A cache writer
5252
* passes the collector it gives the value's encode, so a handle value that
5353
* fails to encode (a rejected pushed promise) refuses the whole entry like a
54-
* failed value does; prerender passes none and keeps the error row.
54+
* failed value does; prerender (prerender-match.ts) passes one too and
55+
* hands the error to its prerender.onError policy.
5556
*/
5657
export async function encodeHandles(
5758
handles: HandleRecord,

0 commit comments

Comments
 (0)