Skip to content
This repository was archived by the owner on Sep 29, 2025. It is now read-only.

Commit a34a582

Browse files
authored
more robust CORS error handling (#847)
* more robust CORS error handling * use "make" pattern
1 parent 393eeeb commit a34a582

File tree

1 file changed

+10
-4
lines changed
  • packages/mongodb-chatbot-server/src

1 file changed

+10
-4
lines changed

packages/mongodb-chatbot-server/src/app.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,14 +62,20 @@ export interface AppConfig {
6262
expressAppConfig?: (app: Express) => Promise<void>;
6363
}
6464

65+
const makeCorsHandler =
66+
(corsOptions?: CorsOptions) =>
67+
(req: ExpressRequest, res: ExpressResponse, next: NextFunction) =>
68+
cors(corsOptions)(req, res, (err) => {
69+
if (err) err.status = 403;
70+
next(err);
71+
});
72+
6573
/**
6674
General error handler. Called at usage of `next()` in routes.
6775
*/
6876
export const errorHandler: ErrorRequestHandler = (err, req, res, _next) => {
6977
const reqId = getRequestId(req);
70-
const isCorsError = err.message.includes("CORS");
71-
72-
const httpStatus = isCorsError ? 403 : err.status || 500;
78+
const httpStatus = err.status || 500;
7379
const errorMessage = err.message || "Internal Server Error";
7480

7581
if (!res.headersSent) {
@@ -142,7 +148,7 @@ export const makeApp = async (config: AppConfig): Promise<Express> => {
142148
// MongoDB chatbot server logic
143149
app.use(makeHandleTimeoutMiddleware(maxRequestTimeoutMs));
144150
app.set("trust proxy", true);
145-
app.use(cors(corsOptions));
151+
app.use(makeCorsHandler(corsOptions));
146152
app.use(express.json());
147153
app.use(reqHandler);
148154
app.use(

0 commit comments

Comments
 (0)