diff --git a/drills/flat-stack-presejpacky/server.ts b/drills/flat-stack-presejpacky/server.ts index 03ecbc8..cc0326d 100644 --- a/drills/flat-stack-presejpacky/server.ts +++ b/drills/flat-stack-presejpacky/server.ts @@ -1,6 +1,7 @@ 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); @@ -8,12 +9,44 @@ const __dirname = path.dirname(__filename); const app = express(); const PORT = process.env.PORT || 3000; +// 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 app.use(express.static(path.join(__dirname, 'dist'))); -// Fallback to index.html for Single Page Application routing +// Fallback to index.html for Single Page Application routing, injecting base path from headers app.get('*', (req, res) => { - res.sendFile(path.join(__dirname, 'dist', 'index.html')); + 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, () => {