Skip to content
Merged
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
52 changes: 52 additions & 0 deletions src/middleware/compress/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,58 @@ describe('Compress Middleware', () => {
})
})

describe('ETag Handling', () => {
const app = new Hono()
app.use('*', compress())
app.get('/strong-etag', (c) => {
c.header('Content-Type', 'text/plain')
c.header('Content-Length', '1024')
c.header('ETag', '"strong-etag"')
return c.text('a'.repeat(1024))
})
app.get('/weak-etag', (c) => {
c.header('Content-Type', 'text/plain')
c.header('Content-Length', '1024')
c.header('ETag', 'W/"weak-etag"')
return c.text('a'.repeat(1024))
})
app.get('/no-etag', (c) => {
c.header('Content-Type', 'text/plain')
c.header('Content-Length', '1024')
return c.text('a'.repeat(1024))
})

it('should convert strong ETag to weak ETag when compressing', async () => {
const res = await app.request('/strong-etag', {
headers: { 'Accept-Encoding': 'gzip' },
})
expect(res.headers.get('Content-Encoding')).toBe('gzip')
expect(res.headers.get('ETag')).toBe('W/"strong-etag"')
})

it('should keep strong ETag when not compressing', async () => {
const res = await app.request('/strong-etag')
expect(res.headers.get('Content-Encoding')).toBeNull()
expect(res.headers.get('ETag')).toBe('"strong-etag"')
})

it('should not modify weak ETag when compressing', async () => {
const res = await app.request('/weak-etag', {
headers: { 'Accept-Encoding': 'gzip' },
})
expect(res.headers.get('Content-Encoding')).toBe('gzip')
expect(res.headers.get('ETag')).toBe('W/"weak-etag"')
})

it('should not add ETag when none exists', async () => {
const res = await app.request('/no-etag', {
headers: { 'Accept-Encoding': 'gzip' },
})
expect(res.headers.get('Content-Encoding')).toBe('gzip')
expect(res.headers.get('ETag')).toBeNull()
})
})

describe('Edge Cases', () => {
it('should not compress responses with Cache-Control: no-transform', async () => {
await testCompression('/no-transform', 'gzip', null)
Expand Down
6 changes: 6 additions & 0 deletions src/middleware/compress/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ export const compress = (options?: CompressionOptions): MiddlewareHandler => {
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)
ctx.res.headers.delete('Content-Length')
ctx.res.headers.set('Content-Encoding', encoding)

// Convert strong ETag to weak ETag since compressed content is not byte-identical
const etag = ctx.res.headers.get('ETag')
if (etag && !etag.startsWith('W/')) {
ctx.res.headers.set('ETag', `W/${etag}`)
}
}
}

Expand Down
Loading