diff --git a/core/templates/tree/react_express/api/app.js b/core/templates/tree/react_express/api/app.js index 7bb10278..7c72a309 100644 --- a/core/templates/tree/react_express/api/app.js +++ b/core/templates/tree/react_express/api/app.js @@ -1,4 +1,6 @@ import path from 'path'; +import { existsSync } from 'fs'; +import { fileURLToPath } from 'node:url'; import cors from 'cors'; import express from 'express'; @@ -9,6 +11,9 @@ import { authenticateWithToken } from './middlewares/authMiddleware.js'; {% endif %} import apiRoutes from './routes/index.js'; +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + // Set up Express app const app = express(); @@ -29,10 +34,22 @@ app.use(authenticateWithToken); app.use(apiRoutes); -app.use(express.static(path.join(import.meta.dirname, "..", "dist"))); +app.use(express.static(path.join(__dirname, "..", "dist"))); -// Assume all other routes are frontend and serve pre-built frontend from ../dist/ folder +// Assume all other routes are frontend app.get(/.*/, async (req, res) => { + // Try to serve pre-built frontend from ../dist/ folder + const clientBundlePath = path.join(__dirname, "..", "dist", "index.html"); + + if (!existsSync(clientBundlePath)) { + if (process.env.NODE_ENV === "development") { + // In development, we just want to redirect to the Vite dev server + return res.redirect("http://localhost:5173"); + } else { + // Looks like "npm run build:ui" wasn't run and the UI isn't built, show a nice error message instead + return res.status(404).send("Front-end not available."); + } + } res.sendFile(path.join(import.meta.dirname, "..", "dist", "index.html")); });