Configure CORS asynchronously
mainIf you need to determine CORS settings dynamically based on the request, you can configure CORS asynchronously. You can do this by passing a callback to fastify.register or by using the delegator key in the options object.
// Method 1: Using a callback in register
fastify.register(require('@fastify/cors'), (instance) => {
return (req, callback) => {
const corsOptions = {
origin: true
};
if (/^localhost$/m.test(req.headers.origin)) {
corsOptions.origin = false
}
callback(null, corsOptions)
}
})
// Method 2: Using the delegator key in options
fastify.register(require('@fastify/cors'), {
hook: 'preHandler',
delegator: (req, callback) => {
const corsOptions = {
origin: true
};
if (/^localhost$/m.test(req.headers.origin)) {
corsOptions.origin = false
}
callback(null, corsOptions)
},
})