Files
Jan Novak afd29c0a23
All checks were successful
Build and Push Presejpacky Docker Image / build-and-push (push) Successful in 7s
feat: add request header logging to dev and prod servers
2026-06-08 00:05:06 +02:00

62 lines
2.0 KiB
TypeScript

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
app.use(express.static(path.join(__dirname, 'dist')));
// 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}`);
});