Skip to content

Commit 1702a19

Browse files
ryansolideverton-dgncursoragent
committed
feat: put the CSP nonce and render mode on the request event
Start middleware is now (event, next), and the page render runs inside next(), so a per-request nonce and render mode are set on the event before the call. The renderMode module form only ever shipped in prereleases and is removed. Co-authored-by: Éverton Toffanetto <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 58e7429 commit 1702a19

14 files changed

Lines changed: 821 additions & 295 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': minor
3+
---
4+
5+
BREAKING: start-mode middleware is event-first, `(event, next) => Response | Promise<Response>`, with the request at `event.request`. The plugin composes the chain itself. `next()` takes no arguments — assign `event.request` before calling it to substitute the request downstream; `next(request)` throws a migration error. Per-request render inputs live on the event, set before `next()` (the render runs inside it): `event.nonce` (a string or `{ script, style }`) and `event.renderMode` (`'stream'` | `'async'`). `handleRequest(request, { nonce, renderMode })` is seeded onto the event before the chain and wins over a middleware write, then the event field, then static `start.renderMode`, then `'stream'`. Invalid host options reject the call before the chain. Generated entries pass `event.nonce` to `renderToStream`; authored entries must forward the `context.nonce` the handler passes them. The injected client-entry script, redirect fallback, dev head, dev styles, and (when there is a style nonce) a `<meta property="csp-nonce">` carry it too. The `start.renderMode` module form, which only shipped in 3.0.0-next prereleases, is removed — a path is a config error pointing at `event.renderMode` in middleware. The static `'stream'` | `'async'` shorthand stays. A nonce set while prerendering the client-mode shell is not baked into `dist/client/index.html` (the build warns). In dev, changing `event.nonce` or `event.renderMode` after the render has read them warns.

‎README.md‎

Lines changed: 57 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -422,42 +422,61 @@ real 3xx redirect, and one set after it (streamed responses) falls back to
422422
a `<script>window.location=...</script>` tail.
423423

424424
**`middleware`** points at a server-only module default-exporting one
425-
fetch-style middleware — `(request, next) => Response | Promise<Response>`
426-
— or an array of them, composed in order:
425+
middleware — `(event, next) => Response | Promise<Response>`, the request
426+
at `event.request` — or an array of them. The plugin composes the chain
427+
itself. `next()` takes no arguments: assign `event.request = new Request(...)`
428+
before calling it to hand a different request downstream (calling
429+
`next(request)`, the previous shape, throws a migration error).
430+
431+
The page render runs inside `next()`, so per-request render inputs go on
432+
the event before that call. `event.nonce` is the CSP nonce (a string, or
433+
`{ script, style }` with each a non-empty string or `false`).
434+
`event.renderMode` is `'stream'` or `'async'` for this request, overriding
435+
the static `renderMode` below.
436+
`handleRequest(request, { nonce, renderMode })` is seeded onto the event
437+
before the chain and wins over a middleware write.
427438

428439
```ts
429440
// vite.config.ts
430441
solid({ start: { middleware: './src/middleware.ts' }, ssr: true });
431442

432443
// src/middleware.ts
433-
import { getRequestEvent } from '@solidjs/web';
434-
435-
export default async function auth(request: Request, next) {
436-
getRequestEvent().locals.user = await userFromCookie(request);
437-
try {
438-
const response = await next();
439-
response.headers.set('server-timing', 'app'); // pre-wire window
440-
return response;
441-
} catch (error) {
442-
return new Response('oops', { status: 500 });
444+
export default async (event, next) => {
445+
event.nonce ??= crypto.randomUUID();
446+
if (/bot|crawler/i.test(event.request.headers.get('user-agent') ?? '')) {
447+
event.renderMode = 'async';
443448
}
444-
}
449+
const response = await next();
450+
const scriptNonce = typeof event.nonce === 'string' ? event.nonce : event.nonce?.script;
451+
if (scriptNonce && response.headers.get('content-type')?.startsWith('text/html')) {
452+
response.headers.set(
453+
'content-security-policy',
454+
`script-src 'nonce-${scriptNonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`,
455+
);
456+
}
457+
return response;
458+
};
445459
```
446460

461+
Generated entries pass `event.nonce` into `renderToStream`. An authored
462+
`entry-server` must forward the `context.nonce` the handler passes it
463+
(`renderToStream(app, { manifest, nonce: context.nonce })`).
464+
447465
The chain fronts every request the plugin dispatches — page SSR and the
448466
server-function endpoint, dev, production, and preview alike — and runs
449-
inside the request-event scope, so `getRequestEvent()` works exactly as in
450-
application code (the endpoint shares the chain's event, so `locals`
467+
inside the request-event scope, so `getRequestEvent()` answers with the
468+
same event as the `event` argument (the endpoint shares it, so `locals`
451469
decoration is visible to server functions too). Nothing reaches the wire
452470
until the outermost middleware returns: headers stay mutable after
453-
`next()` even for streamed responses.
471+
`next()` even for streamed responses. In dev, writing `event.nonce` or
472+
`event.renderMode` after `await next()` warns: the render already read them.
454473

455474
Whatever escapes the chain is settled at the handler edge. A thrown
456475
`Response` is the response, so `throw redirect('/login')` answers the 302
457476
(as the server-function endpoint does), and so is the `Response` a thrown
458477
`respond()` envelope carries; `Response.error()` is not a response and
459478
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
479+
throw, a `setup` failure, or an invalid `event.renderMode` / `event.nonce`) is contained by the
461480
handler instead of rejecting to the host. It is reported once to the hook
462481
registered with `configureServerErrors` from `@solidjs/web`, with the site
463482
a failed render reports (`{ kind: 'render', handling: 'failed' }` and the
@@ -538,7 +557,7 @@ server build must keep code splitting on (the default), since inlining
538557
dynamic imports would hoist the handler graph back above the instrument.
539558

540559
**`renderMode`** — how a page render becomes a response body: `'stream'`
541-
(the default) or `'async'`, or a module path deciding per request.
560+
(the default) or `'async'`.
542561

543562
Streaming flushes the document shell as soon as it is ready, with every
544563
`<Loading>` fallback in place, and streams the boundaries' content behind it
@@ -566,43 +585,33 @@ header written mid-render — the post-flush script redirect in stream mode —
566585
becomes a real 3xx with no body, which is exactly what a no-JS client needs.
567586

568587
Most apps want streaming for browsers and a complete document for the few
569-
clients that cannot run the swap. The per-request form is a module path
570-
(relative to the Vite root, following the `middleware`/`setup` convention
571-
— a Vite config cannot serialize a closure into the generated handler)
572-
default-exporting `(event) => 'stream' | 'async' | Promise<'stream' |
573-
'async'>`. It runs inside the request scope after the middleware chain, so
574-
`event.locals` is decorated by the time it decides:
588+
clients that cannot run the swap. Decide that per request in middleware,
589+
before `next()` — see the middleware example above:
575590

576591
```ts
577-
// vite.config.ts
578-
solid({ start: { renderMode: './src/render-mode.ts' }, ssr: true });
579-
580-
// src/render-mode.ts
581-
import type { RequestEvent } from '@solidjs/web';
582-
583-
const CRAWLER = /Googlebot|bingbot|DuckDuckBot|Slurp|Baiduspider|YandexBot/i;
584-
585-
export default function renderMode(event: RequestEvent) {
586-
const { request } = event;
587-
if (new URL(request.url).searchParams.has('nojs')) return 'async';
588-
if (CRAWLER.test(request.headers.get('user-agent') ?? '')) return 'async';
589-
return 'stream';
592+
if (/bot|crawler/i.test(event.request.headers.get('user-agent') ?? '')) {
593+
event.renderMode = 'async';
590594
}
591595
```
592596

597+
The module form (`renderMode: './src/render-mode.ts'`) shipped only in
598+
3.0.0-next prereleases and is a config error pointing at `event.renderMode`.
599+
593600
Hosts driving the handler directly can decide per call instead:
594601
`handleRequest(request, { renderMode: 'async' })`. Precedence is that
595-
runtime option, then the module function's result, then the static config;
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
599-
mode applies to generated and authored entries alike — an authored
600-
`render()` returning a `renderToStream` result is awaited the same way (and
601-
in production its client-entry reference is still rewritten). `httpStatus()` /
602-
`httpHeader()` declarations survive either mode: the runtime freezes the
603-
response head when the awaited render completes (`@solidjs/web` 2.0.0-rc.7+),
604-
just as streaming freezes it at shell flush. Server mode only — in client mode the served shell has no boundaries to
605-
settle, so the option is a documented no-op there.
602+
option, then `event.renderMode`, then this static value. A bad
603+
`handleRequest` option rejects the call before the chain runs; a bad
604+
`event.renderMode` is a request failure, contained in production like any
605+
other. The mode applies to generated and authored entries alike — an
606+
authored `render()` returning a `renderToStream` result is awaited the same
607+
way (and in production its client-entry reference is still rewritten).
608+
`httpStatus()` / `httpHeader()` declarations survive either mode: the
609+
runtime freezes the response head when the awaited render completes
610+
(`@solidjs/web` 2.0.0-rc.7+), just as streaming freezes it at shell flush.
611+
Server mode only — in client mode the served shell has no boundaries to
612+
settle, so the option is a documented no-op there. A nonce set during the
613+
client-mode shell prerender is ignored (and the build warns): baking one
614+
into `dist/client/index.html` would replay it on every load.
606615

607616
**`env`** — first-party typed environment variables. A schema file at the
608617
project root — `env.ts` (or `env.js`), probed automatically; point
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Prerender nonce fixture (prod mode): vite.config.ts wires this through
2+
// `start.middleware` only when SOLID_SHELL_NONCE=1. The middleware puts a
3+
// CSP nonce on the event while the build prerenders the shell; a nonce baked
4+
// into the static dist/client/index.html would be no nonce at all, so the
5+
// shell must render without it (and the build warns).
6+
import type { StartMiddleware } from '@solidjs/vite-plugin';
7+
8+
const shellNonce: StartMiddleware = (event, next) => {
9+
event.nonce = 'baked-nonce';
10+
return next();
11+
};
12+
13+
export default shellNonce;

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,44 @@ async function prodMode() {
379379
!existsSync(path.join(exampleDir, 'dist/client/index.html')),
380380
);
381381

382+
// A middleware nonce never reaches the prerendered shell: a nonce baked
383+
// into a static file would be replayed on every load. The build warns.
384+
rmSync(path.join(exampleDir, 'dist'), { recursive: true, force: true });
385+
const nonceBuild = await new Promise((resolve) => {
386+
let output = '';
387+
const child = spawn('pnpm', ['exec', 'vite', 'build'], {
388+
cwd: exampleDir,
389+
env: { ...process.env, SOLID_SHELL_NONCE: '1' },
390+
stdio: ['ignore', 'pipe', 'pipe'],
391+
});
392+
children.add(child);
393+
child.stdout.on('data', (d) => (output += d));
394+
child.stderr.on('data', (d) => (output += d));
395+
child.on('exit', (code) => {
396+
children.delete(child);
397+
resolve({ code, output });
398+
});
399+
});
400+
const noncedShellPath = path.join(exampleDir, 'dist/client/index.html');
401+
const noncedShell = existsSync(noncedShellPath) ? readFileSync(noncedShellPath, 'utf-8') : '';
402+
record(
403+
'prod',
404+
'prerender',
405+
'a middleware nonce is not baked into the prerendered shell',
406+
nonceBuild.code === 0 &&
407+
noncedShell.includes('<script') &&
408+
!noncedShell.includes('nonce') &&
409+
!noncedShell.includes('baked-nonce'),
410+
`exit ${nonceBuild.code}`,
411+
);
412+
record(
413+
'prod',
414+
'prerender',
415+
'the build warns that event.nonce is ignored for the client-mode shell',
416+
nonceBuild.output.includes('event.nonce is ignored for the client-mode shell'),
417+
nonceBuild.output.slice(-400),
418+
);
419+
382420
rmSync(path.join(exampleDir, 'dist'), { recursive: true, force: true });
383421
await runCommand('pnpm', ['exec', 'vite', 'build'], { cwd: exampleDir });
384422

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,23 @@ import solidPlugin from '@solidjs/vite-plugin';
2828
// through `start.middleware`: the chain throws while the build prerenders the
2929
// shell, and the build must fail rather than write the handler's contained
3030
// 500 to dist/client/index.html.
31+
//
32+
// SOLID_SHELL_NONCE=1 (prod mode) wires src/shell-nonce.ts instead: the
33+
// chain sets `event.nonce` during the prerender, and the static shell must
34+
// not carry it.
3135
const startNode = !!process.env.SOLID_START_NODE || !!process.env.SOLID_START_NODE_ONLY;
3236
const shellFail = !!process.env.SOLID_SHELL_FAIL;
37+
const shellNonce = !!process.env.SOLID_SHELL_NONCE;
3338
export default defineConfig({
3439
plugins: [
3540
solidPlugin({
3641
start: startNode
3742
? { node: true }
3843
: shellFail
3944
? { middleware: './src/shell-failure.ts' }
40-
: true,
45+
: shellNonce
46+
? { middleware: './src/shell-nonce.ts' }
47+
: true,
4148
ssr: !!process.env.SOLID_FLIP_SSR,
4249
...(process.env.SOLID_START_NODE ? { serverFunctions: true } : {}),
4350
}),

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

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@ import { env } from 'virtual:env/server';
55
// server side sees every var — the secret itself never leaves the server
66
// (only its length does), and ENV_CHECK_PORT arrives as the schema's
77
// *validated output* (a defaulted number, not a raw env string).
8-
export default async function envCheck(
9-
request: Request,
10-
next: (request?: Request) => Promise<Response>,
11-
) {
8+
export default async function envCheck(_event, next: () => Promise<Response>) {
129
const response = await next();
1310
response.headers.set('x-env-secret-len', String(env.SESSION_SECRET.length));
1411
response.headers.set('x-env-port', JSON.stringify(env.ENV_CHECK_PORT));

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

Lines changed: 71 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1-
// Fetch-style middleware chain for the middleware/preview e2e modes
2-
// (SSR_MIDDLEWARE=1 wires it through `start.middleware` in vite.config.ts).
3-
// Server-only: only the generated handler imports it. Exercises the whole
4-
// contract:
5-
// - runs inside the request-event scope: getRequestEvent() answers, locals
6-
// decoration is visible to the page render and to server functions,
1+
// Event-first middleware chain — `(event, next)`, the request at
2+
// `event.request` — for the middleware/preview e2e modes (SSR_MIDDLEWARE=1
3+
// wires it through `start.middleware` in vite.config.ts) and the
4+
// render-mode/nonce modes. Server-only: only the generated handler imports
5+
// it. Exercises the whole contract:
6+
// - runs inside the request-event scope: getRequestEvent() answers with the
7+
// same event, locals decoration is visible to the page render and to
8+
// server functions,
9+
// - per-request render inputs on the event, set before next() (the render
10+
// runs inside it): `renderPolicy` picks `event.renderMode` (a header, a
11+
// crawler user agent, `?nojs` → 'async') and `event.nonce` (test headers),
12+
// and sets the CSP header on HTML responses only; `x-late-nonce` writes
13+
// the nonce after `await next()` — too late, which dev warns about,
714
// - composition order (first → second → dispatch, unwinding in reverse),
815
// - short-circuiting (/blocked never reaches the render), with a stub
916
// cookie set inside the request scope that only the handler edge's
@@ -34,7 +41,9 @@ import {
3441
isResponseEnvelope,
3542
redirect,
3643
respond,
44+
type RequestEvent,
3745
} from '@solidjs/web';
46+
import type { StartMiddleware } from '@solidjs/vite-plugin';
3847
import { failDirect } from './api';
3948

4049
// `start.instrument` evidence (SSR_INSTRUMENT=1): this module evaluates as
@@ -66,14 +75,51 @@ if (process.env.SSR_SERVER_ERRORS) {
6675
});
6776
}
6877

69-
type Next = (request?: Request) => Promise<Response>;
78+
type Next = () => Promise<Response>;
79+
80+
const CRAWLER_UA = /Googlebot|bingbot|DuckDuckBot|Slurp|Baiduspider|YandexBot/i;
81+
82+
// The README recipe: one complete, settled document for clients that will
83+
// never run the streaming swap scripts — crawlers and an explicit `?nojs`
84+
// opt-in — and streaming for everyone else (`x-render-mode` is the test's
85+
// deterministic switch). Plus the CSP nonce: `x-csp-nonce` (a string) or
86+
// `x-csp-nonce-json` (any shape, for the `{ script, style }` pair and the
87+
// validation checks) put it on the event, and the policy header goes on
88+
// HTML responses only.
89+
const renderPolicy: StartMiddleware = async (event, next) => {
90+
const { request } = event;
91+
const header = request.headers.get('x-render-mode');
92+
if (header) event.renderMode = header as RequestEvent['renderMode'];
93+
else if (new URL(request.url).searchParams.has('nojs')) event.renderMode = 'async';
94+
else if (CRAWLER_UA.test(request.headers.get('user-agent') || '')) event.renderMode = 'async';
95+
// What a host's handleRequest nonce looks like from here (seeded onto the
96+
// event before the chain): `event.nonce ??= ...` would adopt it.
97+
if (request.headers.get('x-csp-host')) event.locals.seenNonce = event.nonce ?? null;
98+
const nonce = request.headers.get('x-csp-nonce');
99+
if (nonce) event.nonce = nonce;
100+
const nonceJson = request.headers.get('x-csp-nonce-json');
101+
if (nonceJson) event.nonce = JSON.parse(nonceJson);
102+
const response = await next();
103+
if (request.headers.get('x-late-nonce')) event.nonce = 'too-late';
104+
const scriptNonce = typeof event.nonce === 'string' ? event.nonce : event.nonce?.script;
105+
if (scriptNonce && response.headers.get('content-type')?.startsWith('text/html')) {
106+
response.headers.set(
107+
'content-security-policy',
108+
`script-src 'nonce-${scriptNonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`,
109+
);
110+
}
111+
if (event.locals.seenNonce !== undefined) {
112+
response.headers.set('x-seen-nonce', JSON.stringify(event.locals.seenNonce));
113+
}
114+
return response;
115+
};
70116

71117
// A minimal filesystem-routing/createAPIHandler stand-in: owns /api/* and
72118
// the no-JS form endpoint, passes everything else down the chain.
73-
async function api(request: Request, next: Next): Promise<Response> {
119+
async function api(event: RequestEvent, next: Next): Promise<Response> {
120+
const { request } = event;
74121
const { pathname } = new URL(request.url);
75122
if (request.method === 'GET' && pathname === '/api/info') {
76-
const event = getRequestEvent()!;
77123
return Response.json({ user: event.locals.user, order: event.locals.order });
78124
}
79125
if (request.method === 'GET' && pathname === '/api/server-errors') {
@@ -156,8 +202,10 @@ async function api(request: Request, next: Next): Promise<Response> {
156202
return next();
157203
}
158204

159-
async function first(request: Request, next: Next): Promise<Response> {
160-
const event = getRequestEvent()!;
205+
async function first(event: RequestEvent, next: Next): Promise<Response> {
206+
// The argument and the ambient lookup are the same event.
207+
if (getRequestEvent() !== event) throw new Error('middleware event is not the request event');
208+
const { request } = event;
161209
event.locals.order = ['first'];
162210
event.locals.user = 'mw-user';
163211
const { pathname } = new URL(request.url);
@@ -208,9 +256,18 @@ async function first(request: Request, next: Next): Promise<Response> {
208256
}
209257
}
210258

211-
function second(request: Request, next: Next): Promise<Response> {
212-
(getRequestEvent()!.locals.order as string[]).push('second');
259+
function second(event: RequestEvent, next: Next): Promise<Response> {
260+
(event.locals.order as string[]).push('second');
261+
if (new URL(event.request.url).pathname === '/rewrite-me') {
262+
// Request substitution: assigned on the event before next(), so the
263+
// middleware after this one and the render both see the new request.
264+
event.request = new Request(new URL('/api/info', event.request.url), event.request);
265+
}
266+
if (new URL(event.request.url).pathname === '/next-arg') {
267+
// The retired request-first shape: next() rejects with the migration.
268+
return (next as unknown as (request: Request) => Promise<Response>)(event.request);
269+
}
213270
return next();
214271
}
215272

216-
export default [first, second, api];
273+
export default [renderPolicy, first, second, api];

0 commit comments

Comments
 (0)