Skip to content

Commit 546eca0

Browse files
spellsaifusualoma
andauthored
fix(etag): avoid skipping headers when filtering 304 response headers (#5234)
* fix(etag): avoid skipping headers when filtering 304 response headers * refactor(etag): use Array.from() to snapshot header keys Co-authored-by: Taku Amano <[email protected]>
1 parent 7195c24 commit 546eca0

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,4 +461,33 @@ describe('Etag Middleware', () => {
461461
expect(res.headers.get('ETag')).toBeNull()
462462
})
463463
})
464+
465+
it('Should remove all non-retained headers on 304 without skipping any', async () => {
466+
const app = new Hono()
467+
app.use('/etag/*', etag())
468+
app.get('/etag/multi-headers', (c) => {
469+
c.header('X-Custom-1', 'val1')
470+
c.header('X-Custom-2', 'val2')
471+
c.header('X-Custom-3', 'val3')
472+
c.header('X-Custom-4', 'val4')
473+
c.header('Cache-Control', 'max-age=3600')
474+
return c.text('Hono is hot')
475+
})
476+
const res1 = await app.request('http://localhost/etag/multi-headers')
477+
const etagHeader = res1.headers.get('ETag')!
478+
expect(res1.status).toBe(200)
479+
480+
const res2 = await app.request('http://localhost/etag/multi-headers', {
481+
headers: {
482+
'If-None-Match': etagHeader,
483+
},
484+
})
485+
expect(res2.status).toBe(304)
486+
expect(res2.headers.get('ETag')).toBe(etagHeader)
487+
expect(res2.headers.get('Cache-Control')).toBe('max-age=3600')
488+
expect(res2.headers.get('X-Custom-1')).toBeNull()
489+
expect(res2.headers.get('X-Custom-2')).toBeNull()
490+
expect(res2.headers.get('X-Custom-3')).toBeNull()
491+
expect(res2.headers.get('X-Custom-4')).toBeNull()
492+
})
464493
})

‎src/middleware/etag/index.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,11 +121,11 @@ export const etag = (options?: ETagOptions): MiddlewareHandler => {
121121
ETag: etag,
122122
},
123123
})
124-
c.res.headers.forEach((_, key) => {
124+
for (const key of Array.from(c.res.headers.keys())) {
125125
if (retainedHeaders.indexOf(key.toLowerCase()) === -1) {
126126
c.res.headers.delete(key)
127127
}
128-
})
128+
}
129129
} else {
130130
c.res.headers.set('ETag', etag)
131131
}

0 commit comments

Comments
 (0)