diff --git a/README.md b/README.md index f9adbd7..439a3c4 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,26 @@ fastify.register(async function (fastify) { fastify.listen({ port: 3000 }) ``` +### Disabling CORS for a specific route + +CORS can be disabled at the route level by setting the `cors` option to `false`. + +```js +const fastify = require('fastify')() + +fastify.register(require('@fastify/cors'), { origin: '*' }) + +fastify.get('/cors-enabled', (_req, reply) => { + reply.send('CORS headers') +}) + +fastify.get('/cors-disabled', { cors: false }, (_req, reply) => { + reply.send('No CORS headers') +}) + +fastify.listen({ port: 3000 }) +``` + ### Custom Fastify hook name By default, `@fastify/cors` adds a `onRequest` hook where the validation and header injection are executed. This can be customized by passing `hook` in the options. Valid values are `onRequest`, `preParsing`, `preValidation`, `preHandler`, `preSerialization`, and `onSend`. diff --git a/index.js b/index.js index 2ed7590..2edba47 100644 --- a/index.js +++ b/index.js @@ -171,6 +171,11 @@ function addCorsHeadersHandler (fastify, options, req, reply, next) { return next() } + // Allow routes to disable CORS individually + if (req.routeOptions.config?.cors === false) { + return next() + } + // Falsy values are invalid if (!resolvedOriginOption) { return next(new Error('Invalid CORS origin option')) diff --git a/test/cors.test.js b/test/cors.test.js index 9aacaa9..10aebc2 100644 --- a/test/cors.test.js +++ b/test/cors.test.js @@ -1015,3 +1015,38 @@ test('Should support wildcard config /2', async t => { t.assert.strictEqual(res.payload, 'ok') t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') }) + +test('Should allow routes to disable CORS individually', async t => { + t.plan(6) + + const fastify = Fastify() + fastify.register(cors, { origin: '*' }) + + fastify.get('/cors-enabled', (_req, reply) => { + reply.send('ok') + }) + + fastify.get('/cors-disabled', { config: { cors: false } }, (_req, reply) => { + reply.send('ok') + }) + + // Test CORS enabled route + let res = await fastify.inject({ + method: 'GET', + url: '/cors-enabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') + + // Test CORS disabled route + res = await fastify.inject({ + method: 'GET', + url: '/cors-disabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], undefined) +})