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

server.js

66 lines1.9 KB

1import fs from 'node:fs/promises'
2import express from 'express'
3​
4const isProduction = process.env.NODE_ENV === 'production'
5const port = process.env.PORT || 5173
6const base = process.env.BASE || '/'
7const serverEntry = './dist/server/entry-server.js'
8​
9const templateHtml = isProduction
10 ? await fs.readFile('./dist/client/index.html', 'utf-8')
11 : ''
12​
13const app = express()
14​
15/** @type {import('vite').ViteDevServer | undefined} */
16let vite
17if (!isProduction) {
18 const { createServer } = await import('vite')
19 vite = await createServer({
20 server: { middlewareMode: true },
21 appType: 'custom',
22 base,
23 })
24 app.use(vite.middlewares)
25} else {
26 const compression = (await import('compression')).default
27 const sirv = (await import('sirv')).default
28 app.use(compression())
29 app.use(base, sirv('./dist/client', { extensions: [] }))
31​
32app.use('*all', async (req, res) => {
33 try {
34 const url = req.originalUrl.replace(base, '')
35​
36 /** @type {string} */
37 let template
38 /** @type {typeof import('./src/entry-server').render} */
39 let render
40 if (vite) {
41 template = await fs.readFile('./index.html', 'utf-8')
42 template = await vite.transformIndexHtml(url, template)
43 render = (await vite.ssrLoadModule('/src/entry-server.tsx')).render
44 } else {
45 template = templateHtml
46 render = (await import(serverEntry)).render
47 }
48​
49 const rendered = await render()
50​
51 const html = template
52 .replace(`<!--app-html-->`, rendered.html)
53 .replace(`<!--app-state-->`, rendered.state)
54​
55 res.status(200).set({ 'Content-Type': 'text/html' }).send(html)
56 } catch (error) {
57 const e = /** @type {Error} */ (error)
58 vite?.ssrFixStacktrace(e)
59 console.log(e.stack)
60 res.status(500).end(isProduction ? 'Internal Server Error' : e.stack)
61 }
62})
63​
64app.listen(port, () => {
65 console.log(`Server started at http://localhost:${port}`)
66})