Skip to content

Commit 1907b3f

Browse files
committed
feat(web): event-first middleware and RequestEvent.nonce
FetchMiddleware is now (event, next) => Response, with the request at event.request. next() takes no arguments: a middleware substitutes the request by assigning event.request before calling it, so the event is the single source of truth for what downstream middleware, the handler and the render see. Passing an argument rejects with a migration error. RequestEvent gains nonce?: CSPNonce. renderToString, renderToStream and createSSRResponse fall back to the request event's nonce when no explicit nonce option is passed; the render context carries the resolved value so HydrationScript, streamed scripts, preload links, inline styles and the post-flush redirect fallback get it. An explicit option wins, and null, '' or { script: false, style: false } sends none.
1 parent 893834c commit 1907b3f

6 files changed

Lines changed: 398 additions & 68 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"@solidjs/web": minor
3+
---
4+
5+
Event-first middleware and a per-request CSP nonce on the request event.
6+
7+
**Breaking (prerelease):** `FetchMiddleware` is now `(event, next) => Response | Promise<Response>` — the request is `event.request` — and `composeMiddleware(middlewares)` returns `(event, next) => Promise<Response>`. `next()` takes no arguments: to hand a different request downstream, assign `event.request` before calling it, so the event stays the single source of truth for what later middleware, the handler and the render see. Passing an argument to `next()` rejects with a migration error. `FetchMiddleware` takes an optional event type parameter for integrations with richer events.
8+
9+
`RequestEvent` gains `nonce?: CSPNonce`. `renderToString`, `renderToStream` and `createSSRResponse` fall back to the request event's `nonce` when no explicit `nonce` option is passed, and the render context carries the resolved value, so `<HydrationScript />`, the streamed data/swap scripts, preload links, inline styles and the post-flush redirect fallback all get it. An explicit option wins; an explicit `null`, `""` or `{ script: false, style: false }` renders without one. The event's nonce is read when the render starts — middleware sets it before calling `next()`. `createSSRResponse`'s `nonce` option now accepts the `{ script, style }` form too (its script half is used).

‎documentation/solid-2.0/12-ssr-http.md‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ Server (`@solidjs/web` under the `node`/`deno`/`worker` conditions):
2828

2929
For hydration, the document needs the hydration script ahead of the app markup: `generateHydrationScript({ nonce?, eventNames? })` returns it as a string for hand-built documents, and `<HydrationScript />` renders it in JSX documents.
3030

31+
**CSP nonce.** `renderToString`/`renderToStream` take `nonce` (a string, or a `{ script, style }` pair routing each tag to its CSP directive); it reaches `<HydrationScript />`, the streamed data and swap scripts, preload links and inline styles. Under a request scope the default is the request event's `nonce` field, so a handler or middleware sets it once on the event — before the render starts — and every render and `createSSRResponse` under that request picks it up. An explicit `nonce` option wins; an explicit `null`, `""` or `{ script: false, style: false }` renders without one. Code that authors its own inline scripts reads the same value: `scriptNonce(getRequestEvent()?.nonce)`.
32+
3133
In a hand-built document the render output ends with the serialized hydration records (`_$HY.r`), written by a classic inline `<script>`. The client entry must execute after that script: make it a deferred `<script type="module">` (or a `defer` classic script), or place it after the render output — never `async`, which may run before the records have been parsed and hydrate against an empty document. `<HydrationScript />` documents handle the ordering themselves: the records script is spliced immediately after the bootstrap, so the entry may be `async` there.
3234

3335
### Consuming the stream: `pipe`, `pipeTo`, `readable`
@@ -326,32 +328,36 @@ export function handleRequest(request: Request): Promise<Response> {
326328
- `createSSRResponse(result, event, options?)` accepts a string (from `renderToString`, or an awaited stream) or a `renderToStream` result, and runs the head lifecycle against `event.response`:
327329
- **At shell flush** — the moment the head freezes — the stub is `committed` and its status/headers are merged over `options.responseInit` (`Set-Cookie` values survive as separate entries; `Server-Timing` folds entry by entry; `content-type` defaults to `text/html; charset=utf-8`). The commit is also where the request's trace reaches the head (`Server-Timing: traceparent;desc="…"` — see `getTraceContext()`).
328330
- **A `Location` present before the flush** becomes a real redirect instead of an HTML response: bodyless, carrying the stub’s cookies, with the status from `getExpectedRedirectStatus` (also exported — the stub’s own status when it is a redirect status, `302` otherwise, because a status set for the page render doesn’t describe the redirect that preempts it).
329-
- **A `Location` set after the flush** can only be honored client-side: stream completion appends `<script>window.location=…</script>` before closing, carrying `options.nonce` so a strict `script-src` CSP doesn’t block it.
331+
- **A `Location` set after the flush** can only be honored client-side: stream completion appends `<script>window.location=…</script>` before closing, carrying `options.nonce` (default: `event.nonce`) so a strict `script-src` CSP doesn’t block it.
330332
- **A render that ends before the flush** (it failed, which `onError` hears as `handling: "failed"`, or its `signal` aborted) produced no page: the promise resolves with a bodyless `500` (a `Location` already on the stub still redirects) and the stub is committed. It never rejects.
331333
- `options.transformChunk(chunk)` rewrites each outgoing HTML chunk — the seam handlers use for entry-script injection and doctype prefixes.
332334

333335
String results return a `Response` synchronously; stream results return a promise that resolves at shell flush, so returning it from a fetch handler sends the head at the right moment by construction.
334336

335337
- `commitEventResponse(response, event?)` is the **other exit** — handler-lifecycle plumbing for a `Response` that did not go through `createSSRResponse` (a middleware early return, an API result), the same fold the server-function handler's own responses take. It folds the event's stub onto the response — `Set-Cookie` appends entry-by-entry alongside the response's own, `Server-Timing` folds by name beside the response's own metrics, other stub headers fill gaps only (never the wire-protocol family the handlers own, never `Content-Type`/`Content-Length` on a bodiless response), the status is never taken from the stub — then commits the stub, so later writes fail loudly. An event **without** a `response` stub (the server-function handler's default event, a bare integration) still hands the request's trace on: the response is rebuilt with the `Server-Timing` entries when there is something to say, and comes back untouched otherwise. `event` defaults to the ambient `getRequestEvent()`. It is **idempotent at the handler edge**: an already-committed stub passes the response through untouched, so a handler applies it unconditionally after its middleware chain fully unwinds — page responses come back from `createSSRResponse` committed and do not double-fold. Like `createResponseStub` and `getExpectedRedirectStatus`, this is an integrator-tier export: application middleware never calls it — writes to `event.response` inside the request scope are the application surface; the handler edge runs the fold once.
336338

337-
Handlers compose request middleware with the same web-standard shape everything else uses — `(request, next) => Response | Promise<Response>`:
339+
Handlers compose request middleware over the request event — `(event, next) => Response | Promise<Response>`, with the request at `event.request`:
338340

339341
```ts
340-
import { composeMiddleware, getRequestEvent } from "@solidjs/web";
342+
import { composeMiddleware } from "@solidjs/web";
341343

342344
const run = composeMiddleware([
343-
async (request, next) => {
344-
getRequestEvent()!.locals.user = await authenticate(request);
345+
async (event, next) => {
346+
event.locals.user = await authenticate(event.request);
347+
event.nonce = crypto.randomUUID(); // read by the render inside next()
345348
const response = await next();
346349
response.headers.set("x-served-by", "solid");
347350
return response;
348351
}
349352
]);
353+
354+
// the handler: run(event, () => render(event)) inside provideRequestEvent(event, ...)
350355
```
351356

352-
`next()` advances the chain (an optional `Request` argument substitutes the request downstream); the terminal `next` handed to the composed function dispatches to the actual handler. Two properties are load-bearing:
357+
`next()` advances the chain; the terminal `next` handed to the composed function dispatches to the actual handler. The event is the one source of truth for the request: to hand a different request downstream, assign `event.request` before calling `next()` — `next` takes no arguments (passing one rejects with a migration error), so the request a later middleware, the handler and the render see is always `event.request`. Three properties are load-bearing:
353358

354-
- The chain runs **inside the request scope** the handler established, so `getRequestEvent()` — `locals`, the response stub — works in middleware exactly as it does in application code.
359+
- The chain runs **inside the request scope** the handler established, so `getRequestEvent()` answers with the same event in middleware and in application code.
360+
- The render happens **inside** `next()`: per-request render inputs on the event (`nonce`, an integration's own fields) must be set before calling it — by the time `next()` resolves, the shell has been produced.
355361
- Nothing reaches the wire until the outermost middleware returns: a streamed body hasn’t been consumed yet when `next()` resolves, so headers on the returned `Response` are still mutable through the whole unwind. Error middleware is a plain `try { return await next(); } catch { … }`.
356362

357363
What core deliberately does not ship: routing of middleware (per-path matching), session policy (see the recipe above — cookie _access_ is core, what you build on it is not), and platform adapters — those belong to the layer above, which composes them out of this shape.
@@ -364,7 +370,7 @@ What core deliberately does not ship: routing of middleware (per-path matching),
364370
| `import { getRequestEvent } from "solid-js/web"` | `import { getRequestEvent } from "@solidjs/web"` |
365371
| Start’s `<HttpStatusCode code={404} />` / `<HttpHeader />` components (`@solidjs/start`) | `httpStatus(404)` / `httpHeader(...)` primitives from `@solidjs/web` — core ships functions only |
366372
| Hand-rolled `TransformStream` around `pipeTo` for `Response` bodies | `renderToStream(...).readable` |
367-
| Start’s `createMiddleware` (h3 `Middleware` shapes) | `composeMiddleware` over web-standard `(request, next) => Response` functions |
373+
| Start’s `createMiddleware` (h3 `Middleware` shapes) | `composeMiddleware` over `(event, next) => Response` functions (the request is `event.request`) |
368374
| Hand-rolled head merging / redirect handling in server handlers | `createRequestEvent` + `createSSRResponse` (commit at shell flush, redirect protocol, post-flush script fallback) |
369375
| Start’s `getCookie`/`setCookie` (vinxi/h3 re-exports) | `parseCookieHeader`/`serializeCookie` from `@solidjs/web` over `event.request.headers` / `event.response.headers` — the codec + native `Headers`; jars and sessions are app-layer by ruling (see the sessions recipe) |
370376
| Start’s `useSession` (vinxi/h3 sealed cookies) | app-layer composition — `@remix-run/cookie` (signed, rotating) + the request event, per the sessions recipe; sealed 1.x cookies cannot be verified by a signed helper, so sessions reset (re-login) at the migration boundary |

‎packages/web/src/client.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ import { effect, memo, setSpreadName, spreadName, tagElement } from "./render.js
3838

3939
import { JSX } from "../jsx/jsx.js";
4040

41-
import type { RequestEventLocals, HydrationWriter, HydrationValue } from "./server.js";
41+
import type { RequestEventLocals, HydrationWriter, HydrationValue, CSPNonce } from "./server.js";
4242
import type { TraceContext } from "./trace.js";
4343

4444
type MountableElement = Element | Document | ShadowRoot | DocumentFragment | Node;
@@ -114,6 +114,8 @@ export type { HydrationWriter, HydrationValue } from "./server.js";
114114
export interface RequestEvent {
115115
request: Request;
116116
locals: RequestEventLocals;
117+
/** CSP nonce for server renders under this request (see the server entry). */
118+
nonce?: CSPNonce;
117119
}
118120

119121
export type { CookieOptions } from "./cookies.js";

‎packages/web/src/server-mock.ts‎

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ export type CSPNonce = string | { script: string | false; style: string | false
165165
export function renderToString<T>(
166166
fn: () => T,
167167
options?: {
168-
nonce?: CSPNonce;
168+
nonce?: CSPNonce | null;
169169
renderId?: string;
170170
noScripts?: boolean;
171171
plugins?: any[];
@@ -216,7 +216,7 @@ export function renderToString<T>(
216216
export function renderToStream<T>(
217217
fn: () => T,
218218
options?: {
219-
nonce?: CSPNonce;
219+
nonce?: CSPNonce | null;
220220
renderId?: string;
221221
noScripts?: boolean;
222222
plugins?: any[];
@@ -263,14 +263,15 @@ export function renderToStream<T>(
263263
throwInBrowser(renderToStream);
264264
}
265265
/**
266-
* Fetch-style middleware: receives the `Request` and a `next` continuation
267-
* (pass a `Request` to substitute it downstream) and returns the `Response`.
268-
* Composed with `composeMiddleware`; runs inside the request-event scope, so
269-
* `getRequestEvent()` works exactly as in application code.
266+
* Request middleware: receives the request event (the request is
267+
* `event.request`) and a `next` continuation, and returns the `Response`.
268+
* Assign `event.request` before `next()` to substitute the request
269+
* downstream. Composed with `composeMiddleware`; runs inside the
270+
* request-event scope, so `getRequestEvent()` answers with the same event.
270271
*/
271-
export type FetchMiddleware = (
272-
request: Request,
273-
next: (request?: Request) => Promise<Response>
272+
export type FetchMiddleware<E extends RequestEvent = RequestEvent> = (
273+
event: E,
274+
next: () => Promise<Response>
274275
) => Response | Promise<Response>;
275276

276277
/**
@@ -289,7 +290,7 @@ export function createResponseStub(): ResponseStub {
289290
export function createRequestEvent<T extends object = {}>(
290291
request: Request,
291292
init?: T
292-
): { request: Request; locals: RequestEventLocals; response: ResponseStub } & T {
293+
): RequestEvent & { response: ResponseStub } & T {
293294
throwInBrowser(createRequestEvent);
294295
}
295296

@@ -316,7 +317,7 @@ export function createSSRResponse(
316317
event: RequestEvent | undefined,
317318
options?: {
318319
responseInit?: ResponseInit;
319-
nonce?: string;
320+
nonce?: CSPNonce | null;
320321
transformChunk?: (chunk: string) => string;
321322
}
322323
): Response;
@@ -325,7 +326,7 @@ export function createSSRResponse(
325326
event: RequestEvent | undefined,
326327
options?: {
327328
responseInit?: ResponseInit;
328-
nonce?: string;
329+
nonce?: CSPNonce | null;
329330
transformChunk?: (chunk: string) => string;
330331
}
331332
): Promise<Response>;
@@ -348,17 +349,16 @@ export function commitEventResponse(response: Response, event?: RequestEvent): R
348349
}
349350

350351
/**
351-
* Composes fetch-style middleware — `(request, next) => Response` — into a
352-
* single function of the same shape. Nothing reaches the wire until the
353-
* outermost middleware returns, so headers on the returned `Response` stay
354-
* mutable through the whole unwind, streamed bodies included. Server-only.
352+
* Composes request middleware — `(event, next) => Response` — into a
353+
* single function of the same shape. `next()` takes no arguments: assign
354+
* `event.request` before calling it to substitute the request downstream.
355+
* Nothing reaches the wire until the outermost middleware returns, so
356+
* headers on the returned `Response` stay mutable through the whole
357+
* unwind, streamed bodies included. Server-only.
355358
*/
356-
export function composeMiddleware(
357-
middlewares: FetchMiddleware[]
358-
): (
359-
request: Request,
360-
next: (request?: Request) => Response | Promise<Response>
361-
) => Promise<Response> {
359+
export function composeMiddleware<E extends RequestEvent = RequestEvent>(
360+
middlewares: FetchMiddleware<E>[]
361+
): (event: E, next: () => Response | Promise<Response>) => Promise<Response> {
362362
throwInBrowser(composeMiddleware);
363363
}
364364

0 commit comments

Comments
 (0)