import express from 'express'; import path from 'path'; import { fileURLToPath } from 'url'; import fs from 'fs'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const app = express(); const PORT = process.env.PORT || 3000; // Log all incoming request methods, URLs, and headers app.use((req, res, next) => { console.log(`[Express Request] ${req.method} ${req.url}`); console.log('Headers:', JSON.stringify(req.headers, null, 2)); next(); }); // Middleware to strip base path prefix from request headers if present app.use((req, res, next) => { const prefix = (req.headers['x-forwarded-prefix'] as string) || (req.headers['x-base-path'] as string) || ''; const cleanPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix; if (cleanPrefix && req.url.startsWith(cleanPrefix)) { req.url = req.url.substring(cleanPrefix.length); if (!req.url.startsWith('/')) { req.url = '/' + req.url; } } next(); }); // Serve static files from the 'dist' directory, but bypass index.html requests // so they can be handled dynamically by our fallback route. app.use((req, res, next) => { if (req.url === '/index.html') { return next(); } next(); }); app.use(express.static(path.join(__dirname, 'dist'), { index: false })); // Fallback to index.html for Single Page Application routing, injecting base path from headers app.get('*', (req, res) => { const indexPath = path.join(__dirname, 'dist', 'index.html'); fs.readFile(indexPath, 'utf8', (err, html) => { if (err) { return res.status(500).send('Error reading index.html'); } const prefix = (req.headers['x-forwarded-prefix'] as string) || (req.headers['x-base-path'] as string) || ''; const cleanPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix; // Dynamically prefix asset URLs in index.html with the base path let modifiedHtml = html; if (cleanPrefix) { modifiedHtml = html .replace(/(href|src)="\/assets\//g, `$1="${cleanPrefix}/assets/`) .replace(/(href|src)="\/vite.svg"/g, `$1="${cleanPrefix}/vite.svg"`); } res.send(modifiedHtml); }); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });