|
| 1 | +import { createRequestListener } from "@mjackson/node-fetch-server"; |
| 2 | +import compression from "compression"; |
| 3 | +import express from "express"; |
| 4 | +import { unstable_matchRSCServerRequest as matchRSCServerRequest } from "react-router"; |
| 5 | +import { |
| 6 | + createTemporaryReferenceSet, |
| 7 | + decodeAction, |
| 8 | + decodeFormState, |
| 9 | + decodeReply, |
| 10 | + loadServerAction, |
| 11 | + renderToReadableStream, |
| 12 | + // @ts-expect-error - no types for this yet |
| 13 | +} from "react-server-dom-parcel/server.edge"; |
| 14 | + |
| 15 | +// Import the generateHTML function from the client environment |
| 16 | +import { generateHTML } from "./entry.ssr" with { env: "react-client" }; |
| 17 | +import { routes } from "./routes/config"; |
| 18 | + |
| 19 | +function fetchServer(request: Request) { |
| 20 | + return matchRSCServerRequest({ |
| 21 | + // Provide the React Server touchpoints. |
| 22 | + createTemporaryReferenceSet, |
| 23 | + decodeAction, |
| 24 | + decodeFormState, |
| 25 | + decodeReply, |
| 26 | + loadServerAction, |
| 27 | + // The incoming request. |
| 28 | + request, |
| 29 | + // The app routes. |
| 30 | + routes: routes(), |
| 31 | + // Encode the match with the React Server implementation. |
| 32 | + generateResponse(match) { |
| 33 | + return new Response(renderToReadableStream(match.payload), { |
| 34 | + status: match.statusCode, |
| 35 | + headers: match.headers, |
| 36 | + }); |
| 37 | + }, |
| 38 | + }); |
| 39 | +} |
| 40 | + |
| 41 | +const app = express(); |
| 42 | + |
| 43 | +// Serve static assets with compression and long cache lifetime. |
| 44 | +app.use( |
| 45 | + "/client", |
| 46 | + compression(), |
| 47 | + express.static("dist/client", { |
| 48 | + immutable: true, |
| 49 | + maxAge: "1y", |
| 50 | + }) |
| 51 | +); |
| 52 | +app.use(compression(), express.static("public")); |
| 53 | + |
| 54 | +// Ignore Chrome extension requests. |
| 55 | +app.get("/.well-known/appspecific/com.chrome.devtools.json", (_, res) => { |
| 56 | + res.status(404); |
| 57 | + res.end(); |
| 58 | +}); |
| 59 | + |
| 60 | +// Hookup our application. |
| 61 | +app.use( |
| 62 | + createRequestListener((request) => |
| 63 | + generateHTML( |
| 64 | + request, |
| 65 | + fetchServer, |
| 66 | + (routes as unknown as { bootstrapScript?: string }).bootstrapScript |
| 67 | + ) |
| 68 | + ) |
| 69 | +); |
| 70 | + |
| 71 | +const PORT = Number.parseInt(process.env.PORT || "3000"); |
| 72 | +app.listen(PORT, () => { |
| 73 | + console.log(`Server listening on port ${PORT} (http://localhost:${PORT})`); |
| 74 | +}); |
0 commit comments