hapijs / hapijs/hapi

Preflight CORS issue with `404` routes

Open
#4,397 4 comments 0 reactions 0 assignees View on GitHub
support
Dominant language
JavaScript
Stars
14.8k
Forks
1.4k
Avg merge
22d 3h
Merged PRs (30d)
1

Description

#### Support plan

* *is this issue currently blocking your project?* (yes/no): no
* *is this issue affecting a production system?* (yes/no): no

#### Context

* *node version*: 16.18.0
* *module version with issue*: Hapi 21.0
* *last module version without issue*: 🤷‍♂️
* *environment* (e.g. node, browser, native): node
* *used with* (e.g. hapi application, another framework, standalone, ...): React static app
* *any other relevant information*: CORS issue in any browser (works fine calling the endpoint outside of a browser where CORS doesn't apply), also happens with a simple test web page (no framework)

#### What are you trying to achieve or the steps to reproduce?

With this server code:

```js
import Hapi from '@hapi/hapi'
;(async () => {
const server = Hapi.server({
port: 4001,
host: 'localhost',
routes: {
cors: true,
},
})

server.route({
method: 'GET',
path: '/status',
handler: (request, h) => {
return {
status: 'ok',
}
},
})

await server.start()
console.log('Server running on %s', server.info.uri)
})()

process.on('unhandledRejection', err => {
console.log(err)
process.exit(1)
})
```

Calling a route with `Authorization` headers set causes a preflight request to be sent by the browser, which is accepted by Hapi. However, when the route doesn't exist, Hapi does not allow the CORS request and the browser rejects the response. When the route does exist, the expected CORS headers are added and the request is allowed by the browser (even for other error code ranges).

> **Note**: you can clone the [test code here](https://gist.github.com/gerukin/4092a11eb4acacb23dea897cf4ea4a71).

#### What was the result you got?

From either Chrome or Safari (presumably all browsers), try:

- existent `GET` route, without `Authorization` header (no preflight) => ✅
- non existent `GET` route, without `Authorization` header (no preflight) => ✅
- existent `GET` route, with `Authorization` header (preflight) => ✅
- non existent `GET` route, with `Authorization` header (preflight) => ❌ **CORS error**

#### What result did you expect?

I expected a preflight call to a non existent route to return the default `404` response, with CORS headers added to have the browser allow it to be used.

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.