Open History to see the last commit
1import fs from 'node:fs'
2import path from 'node:path'
3import { toNodeHandler } from 'srvx/node'
4import express from 'express'
5import { createProxyMiddleware } from 'http-proxy-middleware'
6β
7const port = Number(process.env.PORT ?? 3000)
8β
9const startPort = Number(process.env.START_PORT ?? 0)
10β
11const isSpaMode = process.env.MODE === 'spa'
12const isPrerender = process.env.MODE === 'prerender'
13const distDir = process.env.E2E_DIST_DIR || 'dist'
14const distClientDir = path.resolve(distDir, 'client')
15β
16function resolveDistServerEntryPath() {
17 const serverJsPath = path.resolve(distDir, 'server', 'server.js')
18 if (fs.existsSync(serverJsPath)) {
19 return serverJsPath
20 }
21β
22 const indexJsPath = path.resolve(distDir, 'server', 'index.js')
23 if (fs.existsSync(indexJsPath)) {
24 return indexJsPath
25 }
26β
27 return serverJsPath
28}
29β
30export async function createStartServer() {
31 const distServerEntryPath = resolveDistServerEntryPath()
32 const server = (await import(distServerEntryPath)).default
33 const nodeHandler = toNodeHandler(server.fetch)
34β
35 const app = express()
36β
37 // to keep testing uniform stop express from redirecting /posts to /posts/
38 // when serving pre-rendered pages
39 app.use(express.static(distClientDir, { redirect: !isPrerender }))
40β
41 app.use(async (req, res, next) => {
42 try {
43 await nodeHandler(req, res)
44 } catch (error) {
45 next(error)
46 }
47 })
48β
49 return { app }
50}
51β
52export async function createSpaServer(backendPort) {
53 const app = express()
54β
55 app.use(
56 '/api',
57 createProxyMiddleware({
58 target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL
59 changeOrigin: false, // Needed for virtual hosted sites,
60 }),
61 )
62β
63 app.use(
64 '/_serverFn',
65 createProxyMiddleware({
66 target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL
67 changeOrigin: false, // Needed for virtual hosted sites,
68 }),
69 )
70β
71 app.use(express.static(distClientDir))
72β
73 app.get('/{*splat}', (req, res) => {
74 res.sendFile('index.html', { root: distClientDir })
75 })
76β
77 return { app }
78}
79β
80// Bind the backend first so the SPA proxy receives the port actually held by it.
81const { app: startApp } = await createStartServer()
82const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => {
83 if (error) {
84 throw error
85 }
86 const backendPort = backend.address().port
87 if (isSpaMode) {
88 const { app } = await createSpaServer(backendPort)
89 const frontend = app.listen(port, (frontendError) => {
90 if (frontendError) {
91 throw frontendError
92 }
93 console.info(`E2E app: http://localhost:${frontend.address().port}`)
94 })
95 } else {
96 console.info(`E2E app: http://localhost:${backendPort}`)
97 }
98})