Open History to see the last commit
1import path from 'node:path'
2import url from 'node:url'
3import * as fs from 'node:fs'
4import express from 'express'
5import { trpcMiddleWare } from './trpc'
6β
7const PORT =
8 typeof process.env.PORT !== 'undefined'
9 ? parseInt(process.env.PORT, 10)
10 : 3000
11const HMR_PORT =
12 typeof process.env.HMR_PORT !== 'undefined'
13 ? parseInt(process.env.HMR_PORT, 10)
14 : 3001
15β
16const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD
17β
18const __filename = url.fileURLToPath(import.meta.url)
19const __dirname = path.dirname(__filename)
20β
21export const createServer = async (
22 root = process.cwd(),
23 isProd = process.env.NODE_ENV === 'production',
24) => {
25 const app = express()
26β
27 app.use('/trpc', trpcMiddleWare as any)
28β
29 if (!isProd) {
30 const vite = await import('vite')
31 const viteServer = await vite.createServer({
32 root,
33 logLevel: isTest ? 'error' : 'info',
34 server: {
35 middlewareMode: true,
36 watch: {
37 // During tests we edit the files too fast and sometimes chokidar
38 // misses change events, so enforce polling for consistency
39 usePolling: true,
40 interval: 100,
41 },
42 hmr: {
43 port: HMR_PORT,
44 },
45 },
46 appType: 'custom',
47 })
48β
49 // Use vite's connect instance as middleware
50 app.use(viteServer.middlewares)
51β
52 // Handle any requests that don't match an API route by serving the React app's index.html
53 app.get('*', async (req, res, next) => {
54 try {
55 let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8')
56β
57 // Transform HTML using Vite plugins.
58 html = await viteServer.transformIndexHtml(req.url, html)
59β
60 res.send(html)
61 } catch (e) {
62 return next(e)
63 }
64 })
65β
66 return { app }
67 } else {
68 app.use(express.static(path.resolve(__dirname, '../client')))
69β
70 // Handle any requests that don't match an API route by serving the React app's index.html
71 app.get('*', (req, res) => {
72 res.sendFile(path.resolve(__dirname, '../client', 'index.html'))
73 })
74 }
75β
76 return { app }
77}
78β
79if (!isTest) {
80 createServer().then(({ app }) =>
81 app.listen(PORT, () => {
82 console.info(`Server available at: http://localhost:${PORT}`)
83 }),
84 )
85}