I have CORS globally configured like this, to handle credentials:
app.use(cors({ origin: 'https://example.com', credentials: true }))
But on certain routes, I need to allow options requests, so following the documentation, I'm doing something like this:
router.options('/someroute', cors())
router.get('/someroute', cors(), someOtherMiddleware, async (req, res) => {
// do stuff
}
My global CORS policy seems to override the route policy, but only on the options method, I think. I'm trying to come up with a way to make both of these CORS policies play nicely. I have also tried the following, but this doesn't work either. Whichever one I put first seems to override the other one.
app.options('*', cors())
app.use(cors({ origin: 'https://example.com', credentials: true }))
The reason my 2nd code snippet above wasn't working as expected was because I needed to add the preflightContinue property when setting the cors policy at the app level. Otherwise it will ignore cors policies on options routes set at the route level. Kind of a poorly documented thing.
The final solution was to do this at the app level:
app.use(cors({
origin: 'https://example.com',
credentials: true,
preflightContinue: true,
}))
Now this cors policy on the options route actually works:
router.options('/someroute', cors())
router.get('/someroute', cors(), someOtherMiddleware, async (req, res) => {
// do stuff
}
Ugh, spent so long figuring this one out. Hope this saves someone some time.