Skip to content

Commit 76d5589

Browse files
fix(cors): make origin optional in CORSOptions (#4905)
* fix(cors): make origin optional in CORSOptions The CORS middleware applies a default of `origin: '*'` when no value is provided, and the JSDoc already documents `[options.origin='*']` (square brackets indicating optional). The type required `origin`, so calling `cors({ allowMethods: ['GET', 'POST'] })` errored at compile time even though the runtime worked correctly. Make `origin` optional on `CORSOptions` so the type matches the runtime default. No runtime change. Test verifies omitting `origin` produces `Access-Control-Allow-Origin: *` and an explicit `allowMethods` value still applies. Closes #4904 * remove the type error --------- Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
1 parent 8f027e5 commit 76d5589

2 files changed

Lines changed: 21 additions & 6 deletions

File tree

src/middleware/cors/index.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,4 +418,22 @@ describe('CORS by Middleware', () => {
418418
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('null')
419419
expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')
420420
})
421+
422+
it('Options without origin fall back to wildcard default', async () => {
423+
const subApp = new Hono()
424+
subApp.use('/api/*', cors({ allowMethods: ['GET', 'POST'] }))
425+
subApp.get('/api/abc', (c) => c.json({ ok: true }))
426+
427+
const res = await subApp.request('http://localhost/api/abc')
428+
expect(res.status).toBe(200)
429+
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')
430+
431+
const preflight = await subApp.request(
432+
new Request('http://localhost/api/abc', { method: 'OPTIONS' })
433+
)
434+
expect(preflight.headers.get('Access-Control-Allow-Methods')?.split(/\s*,\s*/)).toEqual([
435+
'GET',
436+
'POST',
437+
])
438+
})
421439
})

src/middleware/cors/index.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type { Context } from '../../context'
77
import type { MiddlewareHandler } from '../../types'
88

99
type CORSOptions = {
10-
origin:
10+
origin?:
1111
| string
1212
| string[]
1313
| ((
@@ -61,16 +61,13 @@ type CORSOptions = {
6161
* ```
6262
*/
6363
export const cors = (options?: CORSOptions): MiddlewareHandler => {
64-
const defaults: CORSOptions = {
64+
const opts = {
6565
origin: '*',
6666
allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],
6767
allowHeaders: [],
6868
exposeHeaders: [],
69-
}
70-
const opts = {
71-
...defaults,
7269
...options,
73-
}
70+
} satisfies CORSOptions
7471

7572
const findAllowOrigin = ((optsOrigin) => {
7673
if (typeof optsOrigin === 'string') {

0 commit comments

Comments
 (0)