|
| 1 | +import { PassThrough } from "node:stream"; |
| 2 | + |
| 3 | +import type { AppLoadContext, EntryContext } from "react-router"; |
| 4 | +import { createReadableStreamFromReadable } from "@react-router/node"; |
| 5 | +import { ServerRouter } from "react-router"; |
| 6 | +import { isbot } from "isbot"; |
| 7 | +import type { RenderToPipeableStreamOptions } from "react-dom/server"; |
| 8 | +import { renderToPipeableStream } from "react-dom/server"; |
| 9 | + |
| 10 | +export const streamTimeout = 30_000; |
| 11 | + |
| 12 | +export default function handleRequest( |
| 13 | + request: Request, |
| 14 | + responseStatusCode: number, |
| 15 | + responseHeaders: Headers, |
| 16 | + routerContext: EntryContext, |
| 17 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 18 | + loadContext: AppLoadContext, |
| 19 | + // If you have middleware enabled: |
| 20 | + // loadContext: unstable_RouterContextProvider |
| 21 | +) { |
| 22 | + return new Promise((resolve, reject) => { |
| 23 | + let shellRendered = false; |
| 24 | + const userAgent = request.headers.get("user-agent"); |
| 25 | + |
| 26 | + // Ensure requests from bots and SPA Mode renders wait for all content to load before responding |
| 27 | + // https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation |
| 28 | + const readyOption: keyof RenderToPipeableStreamOptions = |
| 29 | + (userAgent && isbot(userAgent)) || routerContext.isSpaMode |
| 30 | + ? "onAllReady" |
| 31 | + : "onShellReady"; |
| 32 | + |
| 33 | + const { pipe, abort } = renderToPipeableStream( |
| 34 | + <ServerRouter context={routerContext} url={request.url} />, |
| 35 | + { |
| 36 | + [readyOption]() { |
| 37 | + shellRendered = true; |
| 38 | + const body = new PassThrough(); |
| 39 | + const stream = createReadableStreamFromReadable(body); |
| 40 | + |
| 41 | + responseHeaders.set("Content-Type", "text/html"); |
| 42 | + |
| 43 | + resolve( |
| 44 | + new Response(stream, { |
| 45 | + headers: responseHeaders, |
| 46 | + status: responseStatusCode, |
| 47 | + }), |
| 48 | + ); |
| 49 | + |
| 50 | + pipe(body); |
| 51 | + }, |
| 52 | + onShellError(error: unknown) { |
| 53 | + reject(error); |
| 54 | + }, |
| 55 | + onError(error: unknown) { |
| 56 | + responseStatusCode = 500; |
| 57 | + // Log streaming rendering errors from inside the shell. Don't log |
| 58 | + // errors encountered during initial shell rendering since they'll |
| 59 | + // reject and get logged in handleDocumentRequest. |
| 60 | + if (shellRendered) { |
| 61 | + console.error(error); |
| 62 | + } |
| 63 | + }, |
| 64 | + }, |
| 65 | + ); |
| 66 | + |
| 67 | + // Abort the rendering stream after the `streamTimeout` so it has time to |
| 68 | + // flush down the rejected boundaries |
| 69 | + setTimeout(abort, streamTimeout + 1000); |
| 70 | + }); |
| 71 | +} |
0 commit comments