fastify / fastify/fastify-cors

route-level CORS configuration not working for OPTIONS preflight requests

Open
#389 4 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
497
Forks
69
PR merge metrics
No merged PRs in 30d

Description

### Prerequisites

- [x] I have written a descriptive issue title
- [x] I have searched existing issues to ensure the bug has not already been reported

### Fastify version

5.6.2

### Plugin version

_No response_

### Node.js version

v22.21.1

### Operating system

Linux

### Operating system version (i.e. 20.04, 11.3, 10)

24.04

### Description

Hey there,
I wanted to use the newly available route-level CORS configuration ([ref](https://github.com/fastify/fastify-cors/pull/384)).

I discovered that it is not working with OPTIONS preflight requests. IIUC this is because the route level config of the target route can not be resolved since the requests is handled by a wildcard route.
Is there something I am missing or is this not possible with the current implementation?

The only workaround I could think of is to resolve the actual target route and look up the route config but that feels a bit weird. I would be interested in your opinion on this 🙌

```js
test('responds with access-control-allow-origin when using route level config (OPTIONS preflight requests)', async t => {
t.plan(3)

const fastify = Fastify()
fastify.register(cors, {
origin: ['https://default-example.com']
})

fastify.get('/cors', {
config: {
cors: {
origin: 'https://other-domain.com'
}
}
}, (_req, reply) => {
reply.send('CORS headers applied')
})

await fastify.ready()

const resDefault = await fastify.inject({
method: 'OPTIONS',
url: '/cors',
headers: {
'access-control-request-method': 'GET',
origin: 'https://other-domain.com'
}
})

t.assert.ok(resDefault)
t.assert.strictEqual(resDefault.statusCode, 204)
t.assert.strictEqual(resDefault.headers['access-control-allow-origin'], 'https://other-domain.com')
})
```

### Link to code that reproduces the bug

testcase is attached in the issue

### Expected Behavior

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.