Skip to content

Commit 8bf03c3

Browse files
authored
fix(cors): append Origin to Vary header on OPTIONS preflight (#5235)
1 parent 546eca0 commit 8bf03c3

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

‎src/middleware/cors/index.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,34 @@ describe('CORS by Middleware', () => {
277277
expect(res.headers.get('Vary')).toBe('X-Custom-Vary-Value, Origin')
278278
})
279279

280+
it('Append "Origin" to Vary header on OPTIONS preflight, if response has some Vary header', async () => {
281+
const testApp = new Hono()
282+
testApp.use('/api/*', async (c, next) => {
283+
c.header('Vary', 'Accept-Encoding', { append: true })
284+
await next()
285+
})
286+
testApp.use(
287+
'/api/*',
288+
cors({
289+
origin: 'http://example.com',
290+
allowHeaders: ['X-Custom-Header'],
291+
})
292+
)
293+
testApp.all('/api/test', (c) => c.text('ok'))
294+
295+
const res = await testApp.request('http://localhost/api/test', {
296+
method: 'OPTIONS',
297+
headers: {
298+
Origin: 'http://example.com',
299+
'Access-Control-Request-Headers': 'X-Custom-Header',
300+
},
301+
})
302+
303+
expect(res.status).toBe(204)
304+
expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')
305+
expect(res.headers.get('Vary')).toBe('Accept-Encoding, Origin, Access-Control-Request-Headers')
306+
})
307+
280308
it('Allow origins by function', async () => {
281309
let req = new Request('http://localhost/api4/abc', {
282310
headers: {

‎src/middleware/cors/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ export const cors = (options?: CORSOptions): MiddlewareHandler => {
117117

118118
if (c.req.method === 'OPTIONS') {
119119
if (opts.origin !== '*') {
120-
set('Vary', 'Origin')
120+
c.res.headers.append('Vary', 'Origin')
121121
}
122122

123123
if (opts.maxAge != null) {

0 commit comments

Comments
 (0)