From 91fd0918c319519bf20f3bdcb2287a5c85ffa7d1 Mon Sep 17 00:00:00 2001 From: Divyansh <145423867+divyansh355@users.noreply.github.com> Date: Tue, 1 Oct 2024 04:55:14 +0000 Subject: =?UTF-8?q?Enhance=20CORS=20Configuration=20for=20Production=20Sec?= =?UTF-8?q?urity=20=F0=9F=93=8C=20Removed=20the=20wildcard=20(*)=20origin?= =?UTF-8?q?=20and=20replaced=20it=20with=20trusted=20origins=20from=20.env?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 📌 Introduced environment variable (CORS_ALLOWED_ORIGINS) for dynamic origin management. 📌 Improved security by blocking untrusted origins and methods. 📌 Enhanced performance with maxAge for caching preflight responses. 📌 No breaking changes, as the fallback origin is set to http://localhost:4000 for development, ensuring compatibility with local setups. --- src/config/cors.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/config/cors.ts b/src/config/cors.ts index b82f40a..9cbf836 100644 --- a/src/config/cors.ts +++ b/src/config/cors.ts @@ -1,10 +1,25 @@ -import cors from "cors"; +import cors from 'cors'; +import dotenv from 'dotenv'; + +dotenv.config(); + +const allowedOrigins = process.env.CORS_ALLOWED_ORIGINS + ? process.env.CORS_ALLOWED_ORIGINS.split(",") + : ["http://localhost:4000"]; const corsConfig = cors({ - origin: "*", - methods: "GET", + origin: function (origin, callback) { + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + callback(new Error("Not allowed by CORS")); + } + }, + methods: ["GET"], credentials: true, optionsSuccessStatus: 200, + maxAge: 600, }); export default corsConfig; + -- cgit v1.2.3