Skip to content

feat(cors): allowedMethods by function #4060

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/middleware/cors/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ describe('CORS by Middleware', () => {
})
)

app.use(
'/api7/*',
cors({
origin: (origin) => (origin === 'http://example.com' ? origin : '*'),
allowMethods: (origin) =>
origin === 'http://example.com'
? ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE']
: ['GET', 'HEAD'],
})
)

app.get('/api/abc', (c) => {
return c.json({ success: true })
})
Expand All @@ -67,6 +78,10 @@ describe('CORS by Middleware', () => {
return new Response(JSON.stringify({ success: true }))
})

app.get('/api7/abc', () => {
return new Response(JSON.stringify({ success: true }))
})

it('GET default', async () => {
const res = await app.request('http://localhost/api/abc')

Expand Down Expand Up @@ -203,4 +218,26 @@ describe('CORS by Middleware', () => {

expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')
})

it('Allow methods by function', async () => {
const req = new Request('http://localhost/api7/abc', {
headers: {
Origin: 'http://example.com',
},
method: 'OPTIONS',
})
const res = await app.request(req)
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')
expect(res.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD,POST,PATCH,DELETE')

const req2 = new Request('http://localhost/api7/abc', {
headers: {
Origin: 'http://example.org',
},
method: 'OPTIONS',
})
const res2 = await app.request(req2)
expect(res2.headers.get('Access-Control-Allow-Origin')).toBe('*')
expect(res2.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD')
})
})
19 changes: 15 additions & 4 deletions src/middleware/cors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { MiddlewareHandler } from '../../types'

type CORSOptions = {
origin: string | string[] | ((origin: string, c: Context) => string | undefined | null)
allowMethods?: string[]
allowMethods?: string[] | ((origin: string, c: Context) => string[])
allowHeaders?: string[]
maxAge?: number
credentials?: boolean
Expand All @@ -22,7 +22,7 @@ type CORSOptions = {
*
* @param {CORSOptions} [options] - The options for the CORS middleware.
* @param {string | string[] | ((origin: string, c: Context) => string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header.
* @param {string[]} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header.
* @param {string[] | ((origin: string, c: Context) => string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header.
* @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header.
* @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header.
* @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header.
Expand Down Expand Up @@ -80,6 +80,16 @@ export const cors = (options?: CORSOptions): MiddlewareHandler => {
}
})(opts.origin)

const findAllowMethods = ((optsAllowMethods) => {
if (typeof optsAllowMethods === 'function') {
return optsAllowMethods
} else if (Array.isArray(optsAllowMethods)) {
return () => optsAllowMethods
} else {
return () => []
}
})(opts.allowMethods)

return async function cors(c, next) {
function set(key: string, value: string) {
c.res.headers.set(key, value)
Expand Down Expand Up @@ -115,8 +125,9 @@ export const cors = (options?: CORSOptions): MiddlewareHandler => {
set('Access-Control-Max-Age', opts.maxAge.toString())
}

if (opts.allowMethods?.length) {
set('Access-Control-Allow-Methods', opts.allowMethods.join(','))
const allowMethods = findAllowMethods(c.req.header('origin') || '', c)
if (allowMethods.length) {
set('Access-Control-Allow-Methods', allowMethods.join(','))
}

let headers = opts.allowHeaders
Expand Down
Loading