From c3b73c6f990c1199bb2c4c7e7f745169581935f2 Mon Sep 17 00:00:00 2001 From: jikrana Date: Sat, 27 Jun 2026 22:50:49 +0530 Subject: [PATCH] Refactor #495: Moved CORS configuration into a dedicated ES module config/cors.js --- BACKEND/app.js | 21 ++++----------------- BACKEND/config/cors.js | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 17 deletions(-) create mode 100644 BACKEND/config/cors.js diff --git a/BACKEND/app.js b/BACKEND/app.js index 9894ae0..dfbfd4e 100644 --- a/BACKEND/app.js +++ b/BACKEND/app.js @@ -26,7 +26,7 @@ import { stripeWebhook } from "./controllers/checkout.controller.js"; import { expressMiddleware } from "@as-integrations/express4"; import { apolloServer } from "./graphql/server.js"; import { optionalProtect } from "./middleware/auth.js"; - +import corsMiddleware from "./config/cors.js"; // Import error handlers import { notFoundHandler, errorHandler } from "./middleware/errorMiddleware.js"; import { validateEnv } from "./config/env.js"; @@ -115,27 +115,14 @@ app.use( ); app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); app.set("trust proxy", 1); - +app.use(corsMiddleware); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 1000, message: "Too many requests from this IP, please try again later.", }); -const allowedOrigins = [process.env.FRONTEND_URL].filter(Boolean); - -app.use(cors({ - origin: function (origin, callback) { - if (!origin) return callback(null, true); - if (process.env.NODE_ENV !== 'production' && /^http:\/\/localhost:\d+$/.test(origin)) { - return callback(null, true); - } - if (allowedOrigins.includes(origin)) { - return callback(null, true); - } - callback(new Error("CORS Policy Error: Origin not allowed")); - }, - credentials: true -})); + + app.use(passport.initialize()); // Stripe webhook needs raw body — must be registered before express.json() diff --git a/BACKEND/config/cors.js b/BACKEND/config/cors.js new file mode 100644 index 0000000..43e1138 --- /dev/null +++ b/BACKEND/config/cors.js @@ -0,0 +1,23 @@ +import cors from 'cors'; + +const allowedOrigins = [process.env.FRONTEND_URL].filter(Boolean); + +const corsOptions = { + origin: function (origin, callback) { + if (!origin) return callback(null, true); + + if (process.env.NODE_ENV !== 'production' && /^http:\/\/localhost:\d+$/.test(origin)) { + return callback(null, true); + } + + if (allowedOrigins.includes(origin)) { + return callback(null, true); + } + + callback(new Error("CORS Policy Error: Origin not allowed")); + }, + credentials: true +}; + +const corsMiddleware = cors(corsOptions); +export default corsMiddleware; \ No newline at end of file