|
| 1 | +import { PassThrough } from "stream"; |
| 2 | +import { renderToPipeableStream } from "react-dom/server"; |
| 3 | +import { RemixServer } from "@remix-run/react"; |
| 4 | +import { |
| 5 | + createReadableStreamFromReadable, |
| 6 | + type EntryContext, |
| 7 | +} from "@remix-run/node"; |
| 8 | +import { isbot } from "isbot"; |
| 9 | +import { addDocumentResponseHeaders } from "./shopify.server"; |
| 10 | + |
| 11 | +export const streamTimeout = 5000; |
| 12 | + |
| 13 | +export default async function handleRequest( |
| 14 | + request: Request, |
| 15 | + responseStatusCode: number, |
| 16 | + responseHeaders: Headers, |
| 17 | + remixContext: EntryContext |
| 18 | +) { |
| 19 | + addDocumentResponseHeaders(request, responseHeaders); |
| 20 | + const userAgent = request.headers.get("user-agent"); |
| 21 | + const callbackName = isbot(userAgent ?? '') |
| 22 | + ? "onAllReady" |
| 23 | + : "onShellReady"; |
| 24 | + |
| 25 | + return new Promise((resolve, reject) => { |
| 26 | + const { pipe, abort } = renderToPipeableStream( |
| 27 | + <RemixServer |
| 28 | + context={remixContext} |
| 29 | + url={request.url} |
| 30 | + />, |
| 31 | + { |
| 32 | + [callbackName]: () => { |
| 33 | + const body = new PassThrough(); |
| 34 | + const stream = createReadableStreamFromReadable(body); |
| 35 | + |
| 36 | + responseHeaders.set("Content-Type", "text/html"); |
| 37 | + resolve( |
| 38 | + new Response(stream, { |
| 39 | + headers: responseHeaders, |
| 40 | + status: responseStatusCode, |
| 41 | + }) |
| 42 | + ); |
| 43 | + pipe(body); |
| 44 | + }, |
| 45 | + onShellError(error) { |
| 46 | + reject(error); |
| 47 | + }, |
| 48 | + onError(error) { |
| 49 | + responseStatusCode = 500; |
| 50 | + console.error(error); |
| 51 | + }, |
| 52 | + } |
| 53 | + ); |
| 54 | + |
| 55 | + // Automatically timeout the React renderer after 6 seconds, which ensures |
| 56 | + // React has enough time to flush down the rejected boundary contents |
| 57 | + setTimeout(abort, streamTimeout + 1000); |
| 58 | + }); |
| 59 | +} |
0 commit comments