feat: serve client static files + SPA fallback in production

This commit is contained in:
Eugenius-Anonymous
2026-06-08 16:09:34 +07:00
parent e3b618cbef
commit ebb176001f
2 changed files with 23 additions and 3 deletions
+21 -1
View File
@@ -1,6 +1,9 @@
import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import { errorHandler } from './middleware/errorHandler.js';
import { env } from './config/env.js';
// Routes
import authRoutes from './modules/auth/auth.routes.js';
@@ -13,11 +16,14 @@ import reservationRoutes from './modules/reservation/reservation.routes.js';
import billboardRoutes from './modules/billboard/billboard.routes.js';
import paymentRoutes from './modules/payment/payment.routes.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
// Middleware
app.use(cors({
origin: ['http://localhost:5173', 'http://localhost:3000'],
origin: env.NODE_ENV === 'production'
? true // same-origin in production
: ['http://localhost:5173', 'http://localhost:3000'],
credentials: true,
}));
app.use(express.json());
@@ -38,6 +44,20 @@ app.get('/api/health', (_req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// ─── Static files (production) ───────────────────────
// In Docker, client dist is at /app/public
// Locally after build, resolve relative to compiled output
const publicDir = path.resolve(__dirname, '../public');
app.use(express.static(publicDir));
// SPA fallback — serve index.html for all non-API routes
app.get('*', (_req, res, next) => {
const indexPath = path.join(publicDir, 'index.html');
res.sendFile(indexPath, (err) => {
if (err) next(err);
});
});
// Error handler
app.use(errorHandler);