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(); + }); }; }