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

server.js

46 lines1.2 KB

1import fs from 'node:fs'
2import path from 'node:path'
3import express from 'express'
4import { toNodeHandler } from 'srvx/node'
5​
6const port = Number(process.env.PORT ?? 3000)
7const distDir = process.env.E2E_DIST_DIR || 'dist-vite-ssr'
8const distClientDir = path.resolve(distDir, 'client')
9​
10function resolveDistServerEntryPath() {
11 const candidates = [
12 path.resolve(distDir, 'server', 'server.js'),
13 path.resolve(distDir, 'server', 'index.js'),
14 path.resolve(distDir, 'server', 'index.mjs'),
15 ]
16​
17 return (
18 candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0]
19 )
21​
22async function createStartServer() {
23 const server = (await import(resolveDistServerEntryPath())).default
24 const nodeHandler = toNodeHandler(server.fetch)
25 const app = express()
26​
27 app.use(express.static(distClientDir, { redirect: false }))
28 app.use(async (req, res, next) => {
29 try {
30 await nodeHandler(req, res)
31 } catch (error) {
32 next(error)
33 }
34 })
35​
36 return app
38​
39createStartServer().then((app) => {
40 const httpServer = app.listen(port, (error) => {
41 if (error) {
42 throw error
43 }
44 console.info(`E2E app: http://localhost:${httpServer.address().port}`)
45 })
46})