-
-
Notifications
You must be signed in to change notification settings - Fork 704
/
entry-server.tsx
61 lines (55 loc) · 1.51 KB
/
entry-server.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { pipeline } from 'node:stream/promises'
import {
createRequestHandler,
defaultStreamHandler,
} from '@tanstack/start/server'
import { createRouter } from './router'
import type express from 'express'
import './fetch-polyfill'
export async function render({
req,
res,
head,
}: {
head: string
req: express.Request
res: express.Response
}) {
// Convert the express request to a fetch request
const url = new URL(req.originalUrl || req.url, 'https://localhost:3000').href
const request = new Request(url, {
method: req.method,
headers: (() => {
const headers = new Headers()
for (const [key, value] of Object.entries(req.headers)) {
headers.set(key, value as any)
}
return headers
})(),
})
// Create a request handler
const handler = createRequestHandler({
request,
createRouter: () => {
const router = createRouter()
// Update each router instance with the head info from vite
router.update({
context: {
...router.options.context,
head: head,
},
})
return router
},
})
// Let's use the default stream handler to create the response
const response = await handler(defaultStreamHandler)
// Convert the fetch response back to an express response
res.statusMessage = response.statusText
res.status(response.status)
response.headers.forEach((value, name) => {
res.setHeader(name, value)
})
// Stream the response body
return pipeline(response.body as any, res)
}