Open History to see the last commit
1import { pipeline } from 'node:stream/promises'
2import {
3 RouterServer,
4 createRequestHandler,
5 renderRouterToStream,
6} from '@tanstack/solid-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(({ request, responseHeaders, router }) =>
53 renderRouterToStream({
54 request,
55 responseHeaders,
56 router,
57 children: () => <RouterServer router={router} />,
58 }),
59 )
60β
61 // Convert the fetch response back to an express response
62 res.statusMessage = response.statusText
63 res.status(response.status)
64β
65 response.headers.forEach((value, name) => {
66 res.setHeader(name, value)
67 })
68β
69 // Stream the response body
70 return pipeline(response.body as any, res)
71}