Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

server.js

105 lines2.6 KB

1import path from 'node:path'
2import express from 'express'
3import getPort, { portNumbers } from 'get-port'
4import * as zlib from 'node:zlib'
5​
6const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD
7​
8export async function createServer(
9 root = process.cwd(),
10 isProd = process.env.NODE_ENV === 'production',
11 hmrPort,
12) {
13 const app = express()
14​
15 /**
16 * @type {import('vite').ViteDevServer}
17 */
18 let vite
19 if (!isProd) {
20 vite = await (
21 await import('vite')
22 ).createServer({
23 root,
24 logLevel: isTest ? 'error' : 'info',
25 server: {
26 middlewareMode: true,
27 watch: {
28 // During tests we edit the files too fast and sometimes chokidar
29 // misses change events, so enforce polling for consistency
30 usePolling: true,
31 interval: 100,
32 },
33 hmr: {
34 port: hmrPort,
35 },
36 },
37 appType: 'custom',
38 })
39 // use vite's connect instance as middleware
40 app.use(vite.middlewares)
41 } else {
42 app.use(
43 (await import('compression')).default({
44 brotli: {
45 flush: zlib.constants.BROTLI_OPERATION_FLUSH,
46 },
47 flush: zlib.constants.Z_SYNC_FLUSH,
48 }),
49 )
50 }
51​
52 if (isProd) app.use(express.static('./dist/client'))
53​
54 app.use('/{*splat}', async (req, res) => {
55 try {
56 const url = req.originalUrl
57​
58 if (path.extname(url) !== '') {
59 console.warn(`${url} is not valid router path`)
60 res.status(404)
61 res.end(`${url} is not valid router path`)
62 return
63 }
64​
65 // Best effort extraction of the head from vite's index transformation hook
66 let viteHead = !isProd
67 ? await vite.transformIndexHtml(
68 url,
69 `<html><head></head><body></body></html>`,
70 )
71 : ''
72​
73 viteHead = viteHead.substring(
74 viteHead.indexOf('<head>') + 6,
75 viteHead.indexOf('</head>'),
76 )
77​
78 const entry = await (async () => {
79 if (!isProd) {
80 return vite.ssrLoadModule('/src/entry-server.tsx')
81 } else {
82 return import('./dist/server/entry-server.js')
83 }
84 })()
85​
86 console.info('Rendering: ', url, '...')
87 entry.render({ req, res, head: viteHead })
88 } catch (e) {
89 !isProd && vite.ssrFixStacktrace(e)
90 console.info(e.stack)
91 res.status(500).end(e.stack)
92 }
93 })
94​
95 return { app, vite }
97​
98if (!isTest) {
99 createServer().then(async ({ app }) =>
100 app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => {
101 if (error) throw error
102 console.info('Client Server: http://localhost:3000')
103 }),
104 )