const express = require("express"); const cors = require("cors"); const compression = require("compression"); const path = require("path"); const serveStatic = require("serve-static"); const { createProxyMiddleware } = require("http-proxy-middleware"); const app = express(); const port = process.env.PORT || 7860; const apiPort = process.env.INTERNAL_API_PORT || 7861; // Determine if we're in production (Hugging Face Spaces) const isProduction = process.env.NODE_ENV === "production"; // Get the backend URL from environment or use localhost in development const backendUrl = `http://127.0.0.1:${apiPort}`; // Pour production et développement // Enable CORS for all routes app.use(cors()); // Enable GZIP compression app.use(compression()); // Middleware to preserve URL parameters for frontend routes app.use((req, res, next) => { // Preserve original URL parameters req.originalUrl = req.url; next(); }); // Proxy API routes to the Python backend first app.use( [ "/health", "/upload", "/upload-url", "/generate-benchmark", "/benchmark-progress", "/benchmark-questions", "/evaluate-benchmark", "/evaluation-logs", "/evaluation-results", "/download-dataset", "/download-questions", "/cleanup-session", ], createProxyMiddleware({ target: backendUrl, changeOrigin: true, onError: (err, req, res) => { console.error("Proxy Error:", err); res.status(500).json({ error: "Proxy Error", details: err.message }); }, }) ); // Then serve static files from the build directory app.use( express.static(path.join(__dirname, "build"), { // Don't cache HTML files setHeaders: (res, path) => { if (path.endsWith(".html")) { res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); res.setHeader("Pragma", "no-cache"); res.setHeader("Expires", "0"); } else { // Cache other static resources for 1 year res.setHeader("Cache-Control", "public, max-age=31536000"); } }, }) ); // Finally, handle all other routes by serving index.html app.get("*", (req, res) => { // Headers for client-side routing res.set({ "Cache-Control": "no-cache, no-store, must-revalidate", Pragma: "no-cache", Expires: "0", }); // Send index.html for all other routes res.sendFile(path.join(__dirname, "build", "index.html")); }); app.listen(port, "0.0.0.0", () => { console.log( `Frontend server is running on port ${port} in ${ isProduction ? "production" : "development" } mode` ); console.log(`API proxy target: ${backendUrl}`); });