Skip to content

Commit efdaf56

Browse files
committed
fix: contain request failures at the Start handler edge
Fixes #382. handleRequest now settles whatever escapes the start.middleware chain: a thrown Response or response envelope becomes the response, and in production builds any other failure is reported through the configured server error policy and answered with a bodyless 500 instead of rejecting to the host. A client-mode build fails when prerendering the shell answers a non-2xx status.
1 parent 52d93eb commit efdaf56

10 files changed

Lines changed: 508 additions & 12 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@solidjs/vite-plugin': patch
3+
---
4+
5+
The Start handler now settles failures that escape the middleware chain instead of letting them reject to the host. A thrown `Response`, or the `Response` a thrown `respond()` envelope carries, becomes the response in dev and production, so `throw redirect()` works from middleware. In a production build any other failure (a middleware throw, a `start.setup` or `start.renderMode` module failure) is reported once to the `configureServerErrors` hook as `{ kind: 'render', handling: 'failed' }` with the request event, or logged with `console.error` without a hook, and answered with a bodyless 500. That 500 keeps the headers and cookies written to the request event while the response head is still open, that is, unless `next()` already returned a rendered page. In dev those failures still reject, so the dev server sees the original error. An invalid `renderMode` passed to `handleRequest` still rejects the call. A client-mode build now fails when prerendering the shell answers a non-2xx status, instead of writing that response to `index.html`.

‎README.md‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,25 @@ decoration is visible to server functions too). Nothing reaches the wire
452452
until the outermost middleware returns: headers stay mutable after
453453
`next()` even for streamed responses.
454454

455+
Whatever escapes the chain is settled at the handler edge. A thrown
456+
`Response` is the response, so `throw redirect('/login')` answers the 302
457+
(as the server-function endpoint does), and so is the `Response` a thrown
458+
`respond()` envelope carries; `Response.error()` is not a response and
459+
counts as a failure. In a production build any other failure (a middleware
460+
throw, a `setup` or `renderMode` module failure) is contained by the
461+
handler instead of rejecting to the host. It is reported once to the hook
462+
registered with `configureServerErrors` from `@solidjs/web`, with the site
463+
a failed render reports (`{ kind: 'render', handling: 'failed' }` and the
464+
request `event`), or logged with `console.error` when no hook is
465+
registered, and the client gets a bodyless 500. That 500 carries the
466+
headers and cookies written to the request event only while the response
467+
head is still open: once `next()` has returned a rendered page, the head
468+
was committed with that page, and a later throw drops them. An error
469+
middleware still sees a throw first, and with `errorBoundary` on, render
470+
errors are handled by the boundary before they get this far. In dev those
471+
failures still reject, so the dev server sees the original error (with the
472+
built-in dev middleware, Vite's error middleware and its overlay).
473+
455474
**`setup`** points at a server-only module default-exporting a per-request
456475
app-setup hook: `(event, App) => Component | void | Promise<Component |
457476
void>`. The generated server entry awaits it after the middleware chain has
@@ -574,7 +593,9 @@ export default function renderMode(event: RequestEvent) {
574593
Hosts driving the handler directly can decide per call instead:
575594
`handleRequest(request, { renderMode: 'async' })`. Precedence is that
576595
runtime option, then the module function's result, then the static config;
577-
an unknown value from any of the three is an error naming its source. The
596+
an unknown value from any of the three is an error naming its source (a
597+
bad runtime option rejects the `handleRequest` call; a bad module result is
598+
a request failure, contained in production like any other). The
578599
mode applies to generated and authored entries alike — an authored
579600
`render()` returning a `renderToStream` result is awaited the same way (and
580601
in production its client-entry reference is still rewritten). `httpStatus()` /
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Prerender failure fixture (prod mode): vite.config.ts wires this through
2+
// `start.middleware` only when SOLID_SHELL_FAIL=1. The chain throws while
3+
// the build prerenders the shell; the built handler contains that as a
4+
// bodyless 500, and the client-mode build must fail instead of writing the
5+
// 500 to dist/client/index.html.
6+
export default async function shellFailure(): Promise<Response> {
7+
throw new Error('shell-failure-secret');
8+
}

‎examples/start-client/test/run.mjs‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
// script from client-mode shells),
1515
// - build: `vite build` emits a purely static dist/client — index.html is
1616
// the shell prerendered through the built handler, referencing the
17-
// hashed entry script and CSS links — and NO dist/server,
17+
// hashed entry script and CSS links — and NO dist/server; a shell the
18+
// handler answers with a non-2xx status (SOLID_SHELL_FAIL=1: a
19+
// middleware throw it contains as a 500) fails the build instead,
1820
// - preview: `vite preview` serves the static build with history fallback
1921
// and the app boots from it.
2022
//
@@ -334,6 +336,49 @@ async function devMode() {
334336

335337
async function prodMode() {
336338
console.log('\n== prod ==');
339+
// A shell that fails to prerender fails the build. The fixture middleware
340+
// (SOLID_SHELL_FAIL=1) throws while the build prerenders the shell; the
341+
// built handler contains that as a bodyless 500 instead of rejecting, so
342+
// without the check an empty index.html would ship.
343+
rmSync(path.join(exampleDir, 'dist'), { recursive: true, force: true });
344+
const failedBuild = await new Promise((resolve) => {
345+
let output = '';
346+
const child = spawn('pnpm', ['exec', 'vite', 'build'], {
347+
cwd: exampleDir,
348+
env: { ...process.env, SOLID_SHELL_FAIL: '1' },
349+
stdio: ['ignore', 'pipe', 'pipe'],
350+
});
351+
children.add(child);
352+
child.stdout.on('data', (d) => (output += d));
353+
child.stderr.on('data', (d) => (output += d));
354+
child.on('exit', (code) => {
355+
children.delete(child);
356+
resolve({ code, output });
357+
});
358+
});
359+
record(
360+
'prod',
361+
'prerender',
362+
'a shell prerender that answers non-2xx fails the build',
363+
failedBuild.code !== 0 &&
364+
failedBuild.output.includes(
365+
'prerendering the client-mode shell failed: the handler answered 500',
366+
),
367+
`exit ${failedBuild.code}: ${failedBuild.output.slice(-400)}`,
368+
);
369+
record(
370+
'prod',
371+
'prerender',
372+
'the contained failure reaches console.error (no hook registered)',
373+
failedBuild.output.includes('shell-failure-secret'),
374+
);
375+
record(
376+
'prod',
377+
'prerender',
378+
'no dist/client/index.html written for the failed shell',
379+
!existsSync(path.join(exampleDir, 'dist/client/index.html')),
380+
);
381+
337382
rmSync(path.join(exampleDir, 'dist'), { recursive: true, force: true });
338383
await runCommand('pnpm', ['exec', 'vite', 'build'], { cwd: exampleDir });
339384

‎examples/start-client/vite.config.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,21 @@ import solidPlugin from '@solidjs/vite-plugin';
2323
// kept handler. SOLID_START_NODE_ONLY=1 sets `start.node` alone (no server
2424
// functions): the purely static build has no server bundle to wrap, so the
2525
// build warns and emits nothing.
26+
//
27+
// SOLID_SHELL_FAIL=1 (prod mode's failing build) wires src/shell-failure.ts
28+
// through `start.middleware`: the chain throws while the build prerenders the
29+
// shell, and the build must fail rather than write the handler's contained
30+
// 500 to dist/client/index.html.
2631
const startNode = !!process.env.SOLID_START_NODE || !!process.env.SOLID_START_NODE_ONLY;
32+
const shellFail = !!process.env.SOLID_SHELL_FAIL;
2733
export default defineConfig({
2834
plugins: [
2935
solidPlugin({
30-
start: startNode ? { node: true } : true,
36+
start: startNode
37+
? { node: true }
38+
: shellFail
39+
? { middleware: './src/shell-failure.ts' }
40+
: true,
3141
ssr: !!process.env.SOLID_FLIP_SSR,
3242
...(process.env.SOLID_START_NODE ? { serverFunctions: true } : {}),
3343
}),

‎examples/start-ssr/src/api.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,11 @@ export async function nativeAddress() {
5858
export async function configureProbe() {
5959
return 'configure-probe';
6060
}
61+
62+
// Containment probe (src/middleware.ts, /mw-direct-throw): called in-process
63+
// from the outermost middleware and left uncaught. The runtime reports the
64+
// direct call's failure before rethrowing, so the configureServerErrors hook
65+
// must hear it once even though the handler's containment sees it too.
66+
export async function failDirect(): Promise<never> {
67+
throw new Error('token=direct-throw-secret');
68+
}

‎examples/start-ssr/src/middleware.ts‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,25 @@
1717
// with bodies, and no-JS form POSTs must all reach the chain — in dev
1818
// exactly as in production — while non-page requests the chain does NOT
1919
// handle fall back to Vite's own pipeline in dev.
20-
import { getRequestEvent } from '@solidjs/web';
20+
// - failures escaping the whole chain (the handler's containment), all from
21+
// the outermost middleware and outside its try/catch, so nothing in the
22+
// chain catches them: /mw-throw writes a stub cookie and throws an Error
23+
// with a secret-looking message, /mw-throw-late throws after next()
24+
// returned the page, /mw-redirect throws redirect(), /mw-envelope throws a
25+
// respond() envelope, /mw-response-error throws Response.error(),
26+
// /mw-direct-throw lets an in-process server-function failure escape, and
27+
// /setup-throw skips the error middleware so the start.setup failure
28+
// (src/setup.tsx) reaches the handler. SSR_SERVER_ERRORS=1 registers a
29+
// configureServerErrors hook that records what it hears (read back from
30+
// /api/server-errors) instead of logging.
31+
import {
32+
configureServerErrors,
33+
getRequestEvent,
34+
isResponseEnvelope,
35+
redirect,
36+
respond,
37+
} from '@solidjs/web';
38+
import { failDirect } from './api';
2139

2240
// `start.instrument` evidence (SSR_INSTRUMENT=1): this module evaluates as
2341
// part of the handler graph — after `@solidjs/web` above — so what the
@@ -29,6 +47,25 @@ const instrumentAtLoad = globalThis.__solidInstrument
2947
: null;
3048
globalThis.__solidInstrument?.order.push('middleware');
3149

50+
const serverErrors: { message: string; kind: string; handling: string; event: boolean }[] = [];
51+
if (process.env.SSR_SERVER_ERRORS) {
52+
configureServerErrors({
53+
onError(error, { kind, handling, event }) {
54+
// Non-Error values are named by shape so the checks can tell a thrown
55+
// Response (never reported) from Response.error() (a failure).
56+
const message =
57+
error instanceof Error
58+
? error.message
59+
: error instanceof Response
60+
? `Response ${error.status}`
61+
: isResponseEnvelope(error)
62+
? `ResponseEnvelope ${error.response.status}`
63+
: String(error);
64+
serverErrors.push({ message, kind, handling, event: !!event });
65+
},
66+
});
67+
}
68+
3269
type Next = (request?: Request) => Promise<Response>;
3370

3471
// A minimal filesystem-routing/createAPIHandler stand-in: owns /api/* and
@@ -39,6 +76,9 @@ async function api(request: Request, next: Next): Promise<Response> {
3976
const event = getRequestEvent()!;
4077
return Response.json({ user: event.locals.user, order: event.locals.order });
4178
}
79+
if (request.method === 'GET' && pathname === '/api/server-errors') {
80+
return Response.json(serverErrors);
81+
}
4282
if (request.method === 'GET' && pathname === '/api/native') {
4383
// The `options.event` seam: the plugin's dev/preview middlewares (and a
4484
// Node production entry like server.js) pass the raw Node request as
@@ -120,7 +160,31 @@ async function first(request: Request, next: Next): Promise<Response> {
120160
const event = getRequestEvent()!;
121161
event.locals.order = ['first'];
122162
event.locals.user = 'mw-user';
123-
if (new URL(request.url).pathname === '/blocked') {
163+
const { pathname } = new URL(request.url);
164+
if (pathname === '/mw-throw') {
165+
// Uncaught: only the handler's containment can still carry this stub
166+
// cookie onto the wire, and must keep the message off it.
167+
event.response.headers.append('set-cookie', 'mw-throw=1; Path=/');
168+
throw new Error('token=mw-throw-secret');
169+
}
170+
if (pathname === '/mw-throw-late') {
171+
// The page came back (its render committed the stub), then the chain
172+
// fails anyway: contained all the same, with that page dropped.
173+
await next();
174+
throw new Error('token=late-throw-secret');
175+
}
176+
if (pathname === '/mw-redirect') throw redirect('/redirected-target');
177+
if (pathname === '/mw-envelope') {
178+
throw respond({ contained: 'envelope' }, { status: 409, headers: { 'x-envelope': '1' } });
179+
}
180+
if (pathname === '/mw-response-error') throw Response.error();
181+
// The runtime reports a failed in-process server-function call itself
182+
// before rethrowing; the handler must not report it a second time.
183+
if (pathname === '/mw-direct-throw') await failDirect();
184+
// Past the error middleware below on purpose: the start.setup failure
185+
// must escape the chain.
186+
if (pathname === '/setup-throw') return next();
187+
if (pathname === '/blocked') {
124188
// Early return: this Response never goes through createSSRResponse, so
125189
// the stub write below only reaches the wire through the handler
126190
// edge's commitEventResponse fold after the chain unwinds — the e2e

‎examples/start-ssr/src/setup.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,12 @@ export default async function setup(event: RequestEvent, App: Component) {
2626
// Simulates the router's pre-render load; must complete before the shell
2727
// streams, so the marker below always lands in the first chunk.
2828
await new Promise((resolve) => setTimeout(resolve, 10));
29-
const seq = ++invocations;
3029
const pathname = new URL(event.request.url).pathname;
30+
// Containment probe: a setup failure escapes the chain (src/middleware.ts
31+
// lets this path past its error middleware), so the handler contains it.
32+
// Thrown before the count, which stays one per rendered request.
33+
if (pathname === '/setup-throw') throw new Error('token=setup-throw-secret');
34+
const seq = ++invocations;
3135
const user = String((event.locals as Record<string, unknown>).user ?? 'anonymous');
3236
const cookieHeader = event.request.headers.get('cookie');
3337
// One-shot: cleared whether or not it decodes (a tampered or stale cookie

0 commit comments

Comments
 (0)