Open History to see the last commit
1import { pipeline } from 'node:stream/promises'
2import {
3 RouterServer,
4 createRequestHandler,
5 renderRouterToString,
6} from '@tanstack/react-router/ssr/server'
7import { createRouter } from './router'
8import type express from 'express'
9import './fetch-polyfill'
10β
11export async function render({
12 req,
13 res,
14 head,
15}: {
16 head: string
17 req: express.Request
18 res: express.Response
19}) {
20 // Convert the express request to a fetch request
21 const url = new URL(req.originalUrl || req.url, 'https://localhost:3000').href
22β
23 const request = new Request(url, {
24 method: req.method,
25 headers: (() => {
26 const headers = new Headers()
27 for (const [key, value] of Object.entries(req.headers)) {
28 headers.set(key, value as any)
29 }
30 return headers
31 })(),
32 })
33β
34 // Create a request handler
35 const handler = createRequestHandler({
36 request,
37 createRouter: () => {
38 const router = createRouter()
39β
40 // Update each router instance with the head info from vite
41 router.update({
42 context: {
43 ...router.options.context,
44 head: head,
45 },
46 })
47 return router
48 },
49 })
50β
51 // Let's use the default stream handler to create the response
52 const response = await handler(({ responseHeaders, router }) =>
53 renderRouterToString({
54 responseHeaders,
55 router,
56 children: <RouterServer router={router} />,
57 }),
58 )
59β
60 // Convert the fetch response back to an express response
61 res.statusMessage = response.statusText
62 res.status(response.status)
63β
64 response.headers.forEach((value, name) => {
65 res.setHeader(name, value)
66 })
67β
68 // Stream the response body
69 return pipeline(response.body as any, res)
70}