Fix: SPA fallback should be after all routes

This commit is contained in:
salvacybersec
2025-11-11 05:34:02 +03:00
parent 36c5b108ed
commit 3e012be78e

View File

@@ -106,15 +106,6 @@ const frontendDistPath = path.join(__dirname, '../../frontend/dist');
const fs = require('fs'); const fs = require('fs');
if (fs.existsSync(frontendDistPath)) { if (fs.existsSync(frontendDistPath)) {
app.use(express.static(frontendDistPath)); app.use(express.static(frontendDistPath));
// SPA fallback: serve index.html for all non-API routes
app.get('*', (req, res, next) => {
// Skip API routes and tracking routes
if (req.path.startsWith('/api') || req.path.startsWith('/t/') || req.path.startsWith('/health')) {
return next();
}
res.sendFile(path.join(frontendDistPath, 'index.html'));
});
} }
// Session middleware // Session middleware
@@ -153,13 +144,28 @@ app.use('/api/stats', require('./routes/stats.routes'));
// Public tracking route (no rate limit on this specific route) // Public tracking route (no rate limit on this specific route)
app.use('/t', require('./routes/tracking.routes')); app.use('/t', require('./routes/tracking.routes'));
// 404 handler // SPA fallback: serve index.html for all non-API routes (must be after all routes)
app.use((req, res) => { if (fs.existsSync(frontendDistPath)) {
app.get('*', (req, res, next) => {
// Skip API routes and tracking routes
if (req.path.startsWith('/api') || req.path.startsWith('/t/') || req.path.startsWith('/health')) {
return res.status(404).json({
success: false,
error: 'Endpoint not found',
});
}
// Serve frontend SPA
res.sendFile(path.join(frontendDistPath, 'index.html'));
});
} else {
// 404 handler (if frontend not built)
app.use((req, res) => {
res.status(404).json({ res.status(404).json({
success: false, success: false,
error: 'Endpoint not found', error: 'Endpoint not found',
}); });
}); });
}
// Error handler (must be last) // Error handler (must be last)
app.use(errorHandler); app.use(errorHandler);