Skip to content

Commit

Permalink
feat: Dynamically configure CORS based on allowed origins
Browse files Browse the repository at this point in the history
- Update CORS configuration in app.ts to dynamically handle allowed origins.
- Introduce the allowedOrigins field in config.ts.
- Read allowed origins from the environment variable ALLOWED_ORIGINS.
- Improve error handling to reject requests from disallowed origins.

Closes: Dynamically configure CORS using based on allowed origins from the environment variables #24
  • Loading branch information
coderoyalty committed Jan 18, 2024
1 parent 7fe35d2 commit 7e6637f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
20 changes: 13 additions & 7 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express, { Express } from "express";
import morgan from "morgan";
import cors from "cors";
import cors, { CorsOptions } from "cors";
import cookieParser from "cookie-parser";
import BaseController from "./controllers/base.controller";
import errorMiddleWare from "./middlewares/error.middleware";
Expand Down Expand Up @@ -46,12 +46,18 @@ export default class App {
}

private initMiddleware() {
this.app.use(
cors({
origin: "http://localhost:5173",
credentials: true,
}),
);
const allowedOrigins = config.allowedOrigins;
const corsOptions: CorsOptions = {
origin: function (origin: string | undefined, callback: any) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
credentials: true,
};
this.app.use(cors(corsOptions));
this.app.use(cookieParser(config.COOKIE_SECRET));
this.app.use(morgan("dev"));
this.app.use(express.json());
Expand Down
3 changes: 3 additions & 0 deletions backend/src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ const config = {
},
PORT: (process.env.PORT || 5000) as number,
enableLogging: process.env.ENV === "dev" ? true : false,
allowedOrigins: process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(",")
: [],
};

export default config;

0 comments on commit 7e6637f

Please sign in to comment.