From 3e012be78e430ff53579f6072449e6e011dac964 Mon Sep 17 00:00:00 2001 From: salvacybersec Date: Tue, 11 Nov 2025 05:34:02 +0300 Subject: [PATCH] Fix: SPA fallback should be after all routes --- backend/src/app.js | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/backend/src/app.js b/backend/src/app.js index 2006ff9..6245a39 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -106,15 +106,6 @@ const frontendDistPath = path.join(__dirname, '../../frontend/dist'); const fs = require('fs'); if (fs.existsSync(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 @@ -153,13 +144,28 @@ app.use('/api/stats', require('./routes/stats.routes')); // Public tracking route (no rate limit on this specific route) app.use('/t', require('./routes/tracking.routes')); -// 404 handler -app.use((req, res) => { - res.status(404).json({ - success: false, - error: 'Endpoint not found', +// SPA fallback: serve index.html for all non-API routes (must be after all routes) +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({ + success: false, + error: 'Endpoint not found', + }); + }); +} // Error handler (must be last) app.use(errorHandler);