diff options
| author | Divyansh <[email protected]> | 2024-10-01 04:55:14 +0000 |
|---|---|---|
| committer | Divyansh <[email protected]> | 2024-10-01 04:55:14 +0000 |
| commit | 91fd0918c319519bf20f3bdcb2287a5c85ffa7d1 (patch) | |
| tree | 474d38eac226e53e41375ae25582b0cc94e1d3d5 /src/config | |
| parent | dbbd46a99d8690307837e831a8130704e0d63feb (diff) | |
| download | aniwatch-api-91fd0918c319519bf20f3bdcb2287a5c85ffa7d1.tar.xz aniwatch-api-91fd0918c319519bf20f3bdcb2287a5c85ffa7d1.zip | |
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.
Diffstat (limited to 'src/config')
| -rw-r--r-- | src/config/cors.ts | 21 |
1 files changed, 18 insertions, 3 deletions
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; + |
