Enhance CORS Configuration for Production Security

📌 Removed the wildcard (*) origin and replaced it with trusted origins from .env.

📌 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.
This commit is contained in:
Divyansh
2024-10-01 04:55:14 +00:00
parent dbbd46a99d
commit 91fd0918c3
2 changed files with 19 additions and 3 deletions
+1
View File
@@ -1,5 +1,6 @@
DOMAIN = "aniwatchtv.to" DOMAIN = "aniwatchtv.to"
PORT = 4000 PORT = 4000
CORS_ALLOWED_ORIGINS = https://your-production-domain.com,https://another-trusted-domain.com
# RATE LIMIT # RATE LIMIT
WINDOWMS = 1800000 # duration to track requests (in milliseconds) for rate limiting. here, 30*60*1000 = 1800000 = 30 minutes WINDOWMS = 1800000 # duration to track requests (in milliseconds) for rate limiting. here, 30*60*1000 = 1800000 = 30 minutes
+18 -3
View File
@@ -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({ const corsConfig = cors({
origin: "*", origin: function (origin, callback) {
methods: "GET", if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
methods: ["GET"],
credentials: true, credentials: true,
optionsSuccessStatus: 200, optionsSuccessStatus: 200,
maxAge: 600,
}); });
export default corsConfig; export default corsConfig;