PozoAppCommonUpdatedCode/server/server.js

66 lines
2.2 KiB
JavaScript

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import seoMiddleware from './seo-middleware.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
// Configure MIME types for JSX files
app.use((req, res, next) => {
if (req.path.endsWith('.jsx')) {
res.setHeader('Content-Type', 'application/javascript');
}
next();
});
// Serve static assets FIRST (CSS, JS, images, fonts) - these MUST work
// CRITICAL: These must be BEFORE SEO middleware to prevent JS/CSS from being intercepted
// Block /src files in production - they should never be requested
// If requested, return 404 immediately to prevent SEO middleware from intercepting
app.use('/src', (req, res) => {
res.status(404).setHeader('Content-Type', 'text/plain').send('Source files not available in production');
});
// Serve /assets (built files)
app.use('/assets', express.static(path.join(__dirname, '../dist/assets')));
// Serve /og images
app.use('/og', express.static(path.join(__dirname, '../dist/og')));
// Serve all other static files from dist (but NOT index.html)
app.use(express.static(path.join(__dirname, '../dist'), {
index: false, // Don't serve index.html automatically
setHeaders: (res, filePath) => {
// Only block HTML files - let everything else through
if (filePath.endsWith('.html')) {
res.status(404).end();
return;
}
}
}));
// CRITICAL: Explicit handler for /src/ requests - prevent them from reaching SEO middleware
// If static middleware didn't serve it, return 404 instead of falling through
app.use('/src', (req, res, next) => {
// If we reach here, the static middleware didn't find the file
// Return 404 instead of letting it fall through to SEO middleware
res.status(404).setHeader('Content-Type', 'text/plain').send('File not found');
});
// CRITICAL: Apply SEO middleware AFTER static files
// This ensures HTML requests go through SEO middleware
// But static assets are served first
app.use(seoMiddleware);
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log('Dynamic SEO enabled!');
});
export default app;