Skip to content

Commit 66d7d3c

Browse files
authored
fix(router): surface prerender render errors instead of baking them (#587) (#590)
A Prerender route's build-time render error was caught by the router error boundary inside resolveAllSegments, turned into a `type: "error"` segment, and baked as the prerender artifact — then served at runtime as a healthy HTTP 200. The build logged OK and exited 0, so CI/status checks saw a valid 200 while the page was broken (every store category page shipped a "Something Went Wrong" page). The pre-render path now resolves segments with a build-only `throwOnError` flag (matchForPrerender -> resolveAllSegments -> resolveWithErrorBoundary, threaded via ResolveSegmentOptions), so a render failure re-throws to the build loop instead of being converted into an error segment. The live request path leaves the flag unset, so runtime error boundaries are unchanged. `throw new Skip()` inside a render fn now propagates correctly too (it was swallowed by the same boundary). New `rango({ prerender: { onError: "fail" | "warn" } })` option (default "fail"): fail-the-build vs. warn-and-skip, applied in both the prerender and static build loops via the shared resolvePrerenderError helper. Tests: - Unit: prerender-render-error.test.tsx (error surfaced with original message / Skip propagates / healthy render still bakes), driven through matchForPrerender. - E2e: dedicated e2e/prerender-onerror fixture app (own projectRoot, so its dist/ and staged-asset dir never race other e2e builds) + build-level tests for the default-fail and warn paths, for both Prerender routes and Static handlers. - Docs: prerender-api-design.md, feature-map.md, feature-file-map.md, prerender skill. Notes: - prerender.onError "warn" is a build-unblock, not a runtime contract for the skipped entry (it may live-render or 404 depending on the build); use Passthrough()/Skip()/fail for defined behavior. - The dev /__rsc_prerender endpoint change is a cosmetic log refinement on a non-Node-only path; its behavioral change is unit-covered. The endpoint e2e is a deliberate build-only gap (no non-Node buildEnv:off fixture exists).
1 parent c5ee1d7 commit 66d7d3c

24 files changed

Lines changed: 585 additions & 57 deletions

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

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,11 @@ Router option `theme`, `ThemeProvider` integration on server and client, `ThemeS
255255
- `buildEnv` Vite plugin option for build-time `ctx.env` access (KV, D1, etc.)
256256
- `"auto"` mode calls `wrangler.getPlatformProxy()` for Cloudflare presets
257257
- Applies to both production build and dev `/__rsc_prerender` evaluation
258+
- Build-time render errors surface to the build instead of baking an error page
259+
(issue #587): `ResolveSegmentOptions.throwOnError` (set only by the prerender
260+
path) re-throws through `matchForPrerender`. `prerender.onError` Vite plugin
261+
option (`"fail"` default | `"warn"`) chooses fail-the-build vs. warn-and-skip;
262+
`throw new Skip()` inside a render fn skips a single URL/handler
258263

259264
### Request Timeouts
260265

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ route was pre-rendered.
2929
- **Loader freshness** - Loaders always run at request time (never pre-rendered)
3030
- **Dev mode** - On-demand rendering via `/__rsc_prerender` endpoint
3131
- **Intercept pre-rendering** - Intercept variants stored under `/i` key
32+
- **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).
3235

3336
### Remaining
3437

@@ -235,6 +238,54 @@ env — it is shared across all prerender invocations for the build. Without
235238

236239
---
237240

241+
## Render Errors
242+
243+
If a `Prerender` route's render throws at build time, you want to hear about it —
244+
not ship a frozen error page. This started as a bug (#587): the throw was caught by
245+
the route's error boundary _inside_ segment resolution, turned into a normal
246+
`type: "error"` segment, serialized, and baked as the artifact. The build logged
247+
`OK`, exited 0, and at runtime the baked error page was served as a healthy 200.
248+
Status/CI checks saw a valid 200, so a fully broken page looked fine.
249+
250+
The fix: pre-rendering resolves segments with a build-only `throwOnError` flag
251+
(`matchForPrerender` → `resolveAllSegments` → `resolveWithErrorBoundary`, threaded
252+
through `ResolveSegmentOptions`). With it set, a thrown render error is re-thrown
253+
instead of converted into an error segment, so it reaches the build loop
254+
(`expandPrerenderRoutes`). The live request path leaves the flag unset, so runtime
255+
error boundaries are unchanged.
256+
257+
What the build then does is `prerender.onError` (a rango() plugin option):
258+
259+
| build handler outcome | `"fail"` (default) | `"warn"` |
260+
| --------------------------------- | --------------------------------------- | ------------------------- |
261+
| render throws | build fails, names the URL + the error | warn, skip baking the URL |
262+
| `throw new Skip()` in the render | URL skipped (logged `SKIP`) | URL skipped |
263+
| `ctx.passthrough()` (Passthrough) | defer to the live handler (no artifact) | defer to the live handler |
264+
265+
`throw new Skip()` is the per-URL escape hatch: a render that knows it can't run at
266+
build (needs request-time env, say) skips just that URL. This used to be broken too
267+
— a `Skip` thrown in a _render fn_ was swallowed by the same error boundary; it now
268+
propagates correctly (the `getParams()` Skip path always worked).
269+
270+
`"warn"` is a build-unblock, NOT a runtime contract for the skipped entry. At runtime
271+
the route falls through to normal resolution, which may render live (its handler is
272+
still bundled — e.g. when nothing else baked, so handler eviction never ran) or 404
273+
(once eviction has run for other baked entries) — so the outcome depends on the rest
274+
of the build, and a skipped `Static()` segment's evicted code can surface as an error.
275+
For DEFINED runtime behavior use `Passthrough()` (a live fallback) or `throw new
276+
Skip()` (an intentional skip); otherwise prefer the default `"fail"`.
277+
278+
Why no `"dynamic"` or `"bake"` option? `"bake"` is the bug. A clean `"dynamic"`
279+
(always serve live) can't be offered for a plain `Prerender()` route because handler
280+
eviction removes its code when other entries bake; `Passthrough()` is the explicit,
281+
defined way to keep a live fallback. So a render error is either "fail" or "warn".
282+
283+
The same `matchForPrerender` powers the dev `/__rsc_prerender` endpoint, so a render
284+
error in dev surfaces there too: the endpoint logs it and falls through to a live
285+
render rather than serving a frozen error page.
286+
287+
---
288+
238289
## Handler Eviction
239290

240291
In production builds, `Prerender` exports are replaced with stubs:
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import { expect, test } from "@playwright/test";
2+
import path from "node:path";
3+
import { x } from "tinyexec";
4+
5+
/**
6+
* Issue #587 — build-level coverage through the real rango Vite plugin.
7+
*
8+
* Uses a DEDICATED fixture app (e2e/prerender-onerror) with its own projectRoot, so
9+
* its dist/ and staged-asset dir are never shared with — or raced by — any other e2e
10+
* app's build. (The rango plugin's closeBundle writes the prerender/static manifests
11+
* straight into <projectRoot>/dist/rsc regardless of Vite's build.write, so a shared
12+
* app can't be isolated by write:false alone — only a separate projectRoot works.)
13+
*
14+
* The app exports an erroring Prerender route (PrerenderBoom, registered only when
15+
* RANGO_TEST_PRERENDER_ERROR is set; its render reads the unavailable ctx.env) and a
16+
* Static handler (StaticBoom, throws only when RANGO_TEST_STATIC_ERROR is set).
17+
* vite.config flips prerender.onError to "warn" when RANGO_TEST_PRERENDER_ONERROR=warn.
18+
*
19+
* Before the #587 fix the router error boundary swallowed the throw and the build
20+
* baked the error page as a healthy artifact (logged OK, served as a 200). These pin
21+
* the post-fix contract end-to-end through the compiled plugin:
22+
* - default: the build FAILS, naming the URL/handler and the original error;
23+
* - prerender.onError "warn": the build SUCCEEDS and the entry is skipped (not baked);
24+
* - both Prerender routes and Static() handlers go through the same policy.
25+
*
26+
* Build-only by design (explicit gap): #587 is a build-time bug and prerender.onError
27+
* is build config. The dev `/__rsc_prerender` endpoint tweak (router-discovery.ts) is
28+
* a cosmetic log refinement (stay quiet on Skip) on a path that serves ONLY non-Node
29+
* runtimes — and the repo's only non-Node dev fixture (cloudflare-basic) uses
30+
* buildEnv:"auto", where ctx.env is available at build, so the render-error repro
31+
* cannot occur there. The behavioral change (matchForPrerender re-throwing instead of
32+
* baking) is unit-covered (src/router/__tests__/prerender-render-error.test.tsx).
33+
* The endpoint's catch/404-fallthrough is therefore a deliberate untested gap.
34+
*/
35+
const cwd = path.resolve("./e2e/prerender-onerror");
36+
37+
function buildEnv(gates: Record<string, string>): Record<string, string> {
38+
return { ...process.env, ...gates } as Record<string, string>;
39+
}
40+
41+
test.describe("prerender render error (production)", () => {
42+
test.describe.configure({ timeout: 180_000 });
43+
44+
test("fails the build by default, naming the URL and the original error", async () => {
45+
const res = await x("pnpm", ["build"], {
46+
nodeOptions: { cwd, env: buildEnv({ RANGO_TEST_PRERENDER_ERROR: "1" }) },
47+
throwOnError: false,
48+
});
49+
const out = `${res.stdout}\n${res.stderr}`;
50+
expect(
51+
res.exitCode,
52+
`build should exit non-zero; output:\n${out}`,
53+
).not.toBe(0);
54+
// The ORIGINAL render error reaches the build (not a baked error page).
55+
expect(out).toContain("ctx.env is not available during pre-rendering");
56+
expect(out).toMatch(/FAIL\s+\/prerender-boom/);
57+
});
58+
59+
test('prerender.onError "warn" skips the route and the build succeeds', async () => {
60+
const res = await x("pnpm", ["build"], {
61+
nodeOptions: {
62+
cwd,
63+
env: buildEnv({
64+
RANGO_TEST_PRERENDER_ERROR: "1",
65+
RANGO_TEST_PRERENDER_ONERROR: "warn",
66+
}),
67+
},
68+
throwOnError: false,
69+
});
70+
const out = `${res.stdout}\n${res.stderr}`;
71+
expect(
72+
res.exitCode,
73+
`warn build should succeed (exit 0); output:\n${out}`,
74+
).toBe(0);
75+
expect(out).toMatch(/WARN\s+\/prerender-boom.*prerender\.onError: "warn"/);
76+
// Skipped, not baked.
77+
expect(out).toContain("Pre-render complete: 0 done, 1 skipped");
78+
});
79+
80+
test("a Static() handler render error also fails the build by default", async () => {
81+
// No prerender error this run, so the prerender phase succeeds and the build
82+
// reaches renderStaticHandlers, where StaticBoom throws and the same
83+
// prerender.onError policy (default "fail") fails the build.
84+
const res = await x("pnpm", ["build"], {
85+
nodeOptions: { cwd, env: buildEnv({ RANGO_TEST_STATIC_ERROR: "1" }) },
86+
throwOnError: false,
87+
});
88+
const out = `${res.stdout}\n${res.stderr}`;
89+
expect(
90+
res.exitCode,
91+
`static build should exit non-zero; output:\n${out}`,
92+
).not.toBe(0);
93+
expect(out).toContain("static build-time render failure");
94+
expect(out).toMatch(/FAIL\s+StaticBoom/);
95+
});
96+
97+
test('a Static() handler under prerender.onError "warn" is skipped, not baked', async () => {
98+
const res = await x("pnpm", ["build"], {
99+
nodeOptions: {
100+
cwd,
101+
env: buildEnv({
102+
RANGO_TEST_STATIC_ERROR: "1",
103+
RANGO_TEST_PRERENDER_ONERROR: "warn",
104+
}),
105+
},
106+
throwOnError: false,
107+
});
108+
const out = `${res.stdout}\n${res.stderr}`;
109+
expect(
110+
res.exitCode,
111+
`static warn build should succeed (exit 0); output:\n${out}`,
112+
).toBe(0);
113+
expect(out).toMatch(/WARN\s+StaticBoom.*prerender\.onError: "warn"/);
114+
// Skipped, not baked: the static render step reports it as skipped.
115+
expect(out).toContain("Static render complete: 0 done, 1 skipped");
116+
});
117+
});
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "rangojs-e2e-prerender-onerror",
3+
"version": "0.0.0",
4+
"private": true,
5+
"type": "module",
6+
"scripts": {
7+
"build": "vite build",
8+
"typecheck": "tsc --noEmit"
9+
},
10+
"dependencies": {
11+
"@rangojs/router": "workspace:*",
12+
"react": "catalog:",
13+
"react-dom": "catalog:"
14+
},
15+
"devDependencies": {
16+
"@types/react": "catalog:",
17+
"@types/react-dom": "catalog:",
18+
"@vitejs/plugin-react": "catalog:",
19+
"typescript": "^5.3.0",
20+
"vite": "catalog:"
21+
}
22+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Auto-generated by @rangojs/router - do not edit
2+
export const NamedRoutes = {
3+
home: "/",
4+
} as const;
5+
6+
declare global {
7+
namespace Rango {
8+
interface GeneratedRouteMap extends Readonly<typeof NamedRoutes> {}
9+
}
10+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { createRouter, Prerender, Static } from "@rangojs/router";
2+
3+
function HomePage() {
4+
return <h1 data-testid="home">prerender-onerror fixture</h1>;
5+
}
6+
7+
// A Prerender route whose render reads ctx.env, unavailable at build (no buildEnv),
8+
// so it throws during the build-time render (issue #587). Registered only when
9+
// RANGO_TEST_PRERENDER_ERROR is set, so the prerender phase is clean otherwise.
10+
export const PrerenderBoom = Prerender(async (ctx) => {
11+
const region = (ctx as unknown as { env: { REGION: string } }).env.REGION;
12+
return <div data-testid="prerender-boom">{region}</div>;
13+
});
14+
15+
// A Static handler exercising the SAME prerender.onError policy via the
16+
// renderStaticHandlers loop. Static handlers are discovered by export (not route
17+
// registration), so it throws ONLY when RANGO_TEST_STATIC_ERROR is set and renders
18+
// harmlessly otherwise.
19+
export const StaticBoom = Static(() => {
20+
if (process.env.RANGO_TEST_STATIC_ERROR) {
21+
throw new Error("static build-time render failure (#587 fixture)");
22+
}
23+
return <div data-testid="static-boom-ok" />;
24+
});
25+
26+
type AppRoutes = typeof router.routeMap;
27+
28+
declare global {
29+
namespace Rango {
30+
interface RegisteredRoutes extends AppRoutes {}
31+
}
32+
}
33+
34+
export const router = createRouter({}).routes(({ path }) => [
35+
path("/", HomePage, { name: "home" }),
36+
...(process.env.RANGO_TEST_PRERENDER_ERROR
37+
? [path("/prerender-boom", PrerenderBoom)]
38+
: []),
39+
]);
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2022",
4+
"lib": ["ES2023", "DOM", "DOM.Iterable"],
5+
"module": "ESNext",
6+
"skipLibCheck": true,
7+
"moduleResolution": "bundler",
8+
"allowImportingTsExtensions": true,
9+
"isolatedModules": true,
10+
"moduleDetection": "force",
11+
"noEmit": true,
12+
"jsx": "react-jsx",
13+
"strict": true,
14+
"noUncheckedSideEffectImports": true
15+
},
16+
"include": ["src", "vite.config.ts"]
17+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { defineConfig } from "vite";
2+
import react from "@vitejs/plugin-react";
3+
import { rango } from "@rangojs/router/vite";
4+
import { productionDefines } from "../../../../tools/vite-define";
5+
6+
// Dedicated #587 build-fixture app (own projectRoot -> own dist/ and staged-asset
7+
// dir), so the prerender-onerror build tests never share or race the dist/ of any
8+
// other e2e app. `prerender.onError` is flipped to "warn" via env so the same app
9+
// covers both the default-fail and warn paths.
10+
export default defineConfig(({ command }) => ({
11+
plugins: [
12+
react(),
13+
rango(
14+
process.env.RANGO_TEST_PRERENDER_ONERROR === "warn"
15+
? { prerender: { onError: "warn" } }
16+
: undefined,
17+
),
18+
],
19+
define: productionDefines(command),
20+
}));

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

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -343,14 +343,31 @@ export const TocSidebar = Static(() => {
343343

344344
### Error behavior at build time
345345

346-
| Handler outcome | Effect |
347-
| --------------------------- | ----------------------------------------------------- |
348-
| JSX / `null` | Normal prerender entry, log OK |
349-
| `return ctx.passthrough()` | Skip entry, log PASS, continue (Passthrough routes) |
350-
| `throw new Skip("reason")` | Skip entry, log SKIP, continue with remaining entries |
351-
| `throw new Error("reason")` | Log FAIL, stop ALL pre-rendering, fail the build |
352-
353-
Both error types propagate to the router's `onError` callback with phase
346+
When a render throws a non-`Skip` error, it is **surfaced to the build** — never
347+
baked into a frozen error page served as a 200 (issue #587). What happens next is
348+
controlled by `prerender.onError` in your `rango()` options:
349+
350+
```ts
351+
rango({ prerender: { onError: "warn" } }); // default is "fail"
352+
```
353+
354+
| Handler outcome | `onError: "fail"` (default) | `onError: "warn"` |
355+
| --------------------------- | -------------------------------------------- | -------------------------------- |
356+
| JSX / `null` | Normal prerender entry, log OK | Normal prerender entry, log OK |
357+
| `return ctx.passthrough()` | Skip entry, log PASS (Passthrough routes) | Skip entry, log PASS |
358+
| `throw new Skip("reason")` | Skip entry, log SKIP, continue | Skip entry, log SKIP, continue |
359+
| `throw new Error("reason")` | Log FAIL, stop ALL pre-rendering, fail build | Log WARN, skip the URL, continue |
360+
361+
With `"warn"` the errored entry is logged and left un-baked (never served as a baked
362+
200 error page). `"warn"` is a build-unblock, not a runtime contract: the route falls
363+
through to normal resolution — it may render live (its handler is still bundled) or
364+
404 (once other baked entries trigger prerender handler eviction), so the outcome
365+
depends on the rest of the build, and a skipped `Static()` handler's evicted code can
366+
surface as an error. For DEFINED runtime behavior reach for `Passthrough()` (a live
367+
fallback) or `throw new Skip()` (an intentional skip — works in the render fn, not
368+
only `getParams()`); otherwise prefer the default `"fail"`.
369+
370+
Both `Skip` and hard errors propagate to the router's `onError` callback with phase
354371
`"prerender"` or `"static"`.
355372

356373
### Build logs
@@ -370,9 +387,11 @@ The build produces per-URL timing logs:
370387
[rango] Static render complete: 2 done, 1 skipped (120ms total)
371388
```
372389

373-
A `FAIL` line is logged per-URL when a handler throws a non-Skip error. The
374-
error is re-thrown immediately, so no summary line is printed — the build
375-
stops at the first failure.
390+
A `FAIL` line is logged per-URL when a handler throws a non-Skip error (with the
391+
default `prerender.onError: "fail"`). The error is re-thrown immediately, so no
392+
summary line is printed — the build stops at the first failure. Under
393+
`prerender.onError: "warn"` the same case logs a `WARN` line, skips that URL, and
394+
the build continues.
376395

377396
### Dev mode behavior
378397

0 commit comments

Comments
 (0)