From c48ec398345f61376e913dc0d48c50822009dfb5 Mon Sep 17 00:00:00 2001 From: MAZHAR ANSARI <113109217+M-zhar@users.noreply.github.com> Date: Fri, 29 Nov 2024 00:18:15 +0530 Subject: [PATCH] Update index.js Setting Vary: Origin Header for All Requests: The res.setHeader('Vary', 'Origin') line ensures that every response includes the Vary: Origin header, regardless of whether it's a CORS or non-CORS request. //CORS Middleware for Requests with Origin: The dynamic cors middleware is applied only if the originCallback function validates the origin. //Non-CORS Requests: For requests without the Origin header, the middleware still sets the Vary: Origin header and proceeds without invoking the cors middleware. --- lib/index.js | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/lib/index.js b/lib/index.js index ad899ca..cc03bff 100644 --- a/lib/index.js +++ b/lib/index.js @@ -215,20 +215,26 @@ }; } - if (originCallback) { - originCallback(req.headers.origin, function (err2, origin) { - if (err2 || !origin) { - next(err2); - } else { - corsOptions.origin = origin; - cors(corsOptions, req, res, next); - } - }); - } else { - next(); - } - } - }); + if (originCallback) { + app.use((req, res, next) => { + // Set the Vary: Origin header for all responses + res.setHeader('Vary', 'Origin'); + // Handle CORS requests dynamically + originCallback(req.headers.origin, function (err2, origin) { + if (err2 || !origin) { + next(err2 || new Error('Origin not allowed')); + } else { + const corsOptions = { origin }; // Create corsOptions dynamically + cors(corsOptions)(req, res, next); // Apply CORS middleware dynamically + } + }); + }); +} else { + app.use((req, res, next) => { + // Always set Vary: Origin, even for non-CORS requests + res.setHeader('Vary', 'Origin'); + next(); + }); }; }