Skip to content
Myr

fix(compress): convert strong ETag to weak ETag when compressing (#4848)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Compressed content is not byte-identical to the original, so strong ETags violate HTTP semantics (RFC 9110). Convert them to weak ETags by adding the W/ prefix, matching the behavior of nginx, Apache, and Express.

authored by Taku Amano · committed by GitHub · parent 75b4308 · Browse files · 2 files+58 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+58 added−0 removed

  • tests:+52 added−0 removed
  • other:+6 added−0 removed

2 files+58 added−0 removed

modified:src/middleware/compress/index.test.ts+52 added
191 unmodified lines
192 expect((await res.arrayBuffer()).byteLength).toBe(13000)193 })194 })195196 describe('ETag Handling', () => {197 const app = new Hono()198 app.use('*', compress())199 app.get('/strong-etag', (c) => {200 c.header('Content-Type', 'text/plain')201 c.header('Content-Length', '1024')202 c.header('ETag', '"strong-etag"')203 return c.text('a'.repeat(1024))204 })205 app.get('/weak-etag', (c) => {206 c.header('Content-Type', 'text/plain')207 c.header('Content-Length', '1024')208 c.header('ETag', 'W/"weak-etag"')209 return c.text('a'.repeat(1024))210 })211 app.get('/no-etag', (c) => {212 c.header('Content-Type', 'text/plain')213 c.header('Content-Length', '1024')214 return c.text('a'.repeat(1024))215 })216217 it('should convert strong ETag to weak ETag when compressing', async () => {218 const res = await app.request('/strong-etag', {219 headers: { 'Accept-Encoding': 'gzip' },220 })221 expect(res.headers.get('Content-Encoding')).toBe('gzip')222 expect(res.headers.get('ETag')).toBe('W/"strong-etag"')223 })224225 it('should keep strong ETag when not compressing', async () => {226 const res = await app.request('/strong-etag')227 expect(res.headers.get('Content-Encoding')).toBeNull()228 expect(res.headers.get('ETag')).toBe('"strong-etag"')229 })230231 it('should not modify weak ETag when compressing', async () => {232 const res = await app.request('/weak-etag', {233 headers: { 'Accept-Encoding': 'gzip' },234 })235 expect(res.headers.get('Content-Encoding')).toBe('gzip')236 expect(res.headers.get('ETag')).toBe('W/"weak-etag"')237 })238239 it('should not add ETag when none exists', async () => {240 const res = await app.request('/no-etag', {241 headers: { 'Accept-Encoding': 'gzip' },242 })243 expect(res.headers.get('Content-Encoding')).toBe('gzip')244 expect(res.headers.get('ETag')).toBeNull()245 })246 })247248 describe('Edge Cases', () => {249 it('should not compress responses with Cache-Control: no-transform', async () => {250 await testCompression('/no-transform', 'gzip', null)251 })
24 unmodified lines
modified:src/middleware/compress/index.ts+6 added