Open History to see the last commit
1import fs from 'node:fs'
2import path from 'node:path'
3import { fileURLToPath } from 'node:url'
4import express from 'express'
5β
6const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD
7β
8process.env.MY_CUSTOM_SECRET = 'API_KEY_qwertyuiop'
9β
10export async function createServer(
11 root = process.cwd(),
12 isProd = process.env.NODE_ENV === 'production',
13 hmrPort,
14) {
15 const app = express()
16β
17 /**
18 * @type {import('vite').ViteDevServer}
19 */
20 let vite
21 if (!isProd) {
22 vite = await (
23 await import('vite')
24 ).createServer({
25 root,
26 logLevel: isTest ? 'error' : 'info',
27 server: {
28 middlewareMode: true,
29 watch: {
30 // During tests we edit the files too fast and sometimes chokidar
31 // misses change events, so enforce polling for consistency
32 usePolling: true,
33 interval: 100,
34 },
35 hmr: {
36 port: hmrPort,
37 },
38 },
39 appType: 'custom',
40 })
41 // use vite's connect instance as middleware
42 app.use(vite.middlewares)
43 } else {
44 app.use((await import('compression')).default())
45 }
46β
47 app.use('*', async (req, res) => {
48 try {
49 const url = req.originalUrl
50β
51 if (url.includes('.')) {
52 console.warn(`${url} is not valid router path`)
53 res.status(404)
54 res.end(`${url} is not valid router path`)
55 return
56 }
57β
58 // Extract the head from vite's index transformation hook
59 let viteHead = !isProd
60 ? await vite.transformIndexHtml(
61 url,
62 `<html><head></head><body></body></html>`,
63 )
64 : ''
65β
66 viteHead = viteHead.substring(
67 viteHead.indexOf('<head>') + 6,
68 viteHead.indexOf('</head>'),
69 )
70β
71 const entry = await (async () => {
72 if (!isProd) {
73 return vite.ssrLoadModule('/src/entry-server.tsx')
74 } else {
75 return import('./dist/server/entry-server.tsx')
76 }
77 })()
78β
79 // Since the router can also be used simply to fulfill data,
80 // Request for data, not html
81 if (url.includes('__data=')) {
82 const data = await entry.load({
83 url,
84 })
85 return res.json(data)
86 }
87β
88 // Control/hydrate all the way up to <html>
89 // Modify head
90 // Request/Response control at the route level
91β
92 console.log('Rendering: ', url, '...')
93 entry.render({ req, res, url, head: viteHead })
94 } catch (e) {
95 !isProd && vite.ssrFixStacktrace(e)
96 console.log(e.stack)
97 res.status(500).end(e.stack)
98 }
99 })
100β
101 return { app, vite }
102}
103β
104if (!isTest) {
105 createServer().then(({ app }) =>
106 app.listen(3000, () => {
107 console.log('Client Server: http://localhost:3000')
108 }),
109 )
110}