Skip to content

Commit f0ed246

Browse files
LeSingh1yusukebeusualoma
authored
fix(compress): respect Accept-Encoding when encoding option is set (#4951)
* fix(compress): skip compression when client does not accept the configured encoding When the encoding option is set, the middleware previously compressed responses unconditionally, regardless of the Accept-Encoding header. This could send a response in an encoding the client cannot decode (for example, returning gzip when the client only advertised deflate, or when Accept-Encoding is absent). Honor the client's Accept-Encoding header even when an encoding is explicitly configured, falling back to no compression when the configured encoding is not accepted. * fix(compress): use parseAccept to honor q-values, wildcard, and case Address review from @yusukebe. The previous version used String.includes on the raw Accept-Encoding header, which treated x-gzip as gzip, ignored q=0 explicit refusals, and did not understand the wildcard. Switch to parseAccept (already used by accepts middleware) and pick the candidate encoding with the highest non-zero q value, falling back to the wildcard q if the candidate has no explicit entry. Add seven regression tests covering q=0 on the configured encoding, q=0 fallback to another candidate, wildcard \*, case-insensitive tokens, x-gzip non-matching, highest-q wins, and gzip-over-deflate tie-break. * fix(compress): short-circuit selectEncoding when q is 1 Per @usualoma: q values are almost always 1 in practice, so short-circuit and return immediately for the common path instead of continuing to scan the remaining candidates. Co-authored-by: Yusuke Wada <[email protected]> Co-authored-by: Taku Amano <[email protected]>
1 parent a192df0 commit f0ed246

2 files changed

Lines changed: 142 additions & 3 deletions

File tree

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

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,121 @@ describe('Compress Middleware', () => {
266266
expect(decompressed).toBe('Custom NotFound')
267267
})
268268
})
269+
270+
describe('Encoding Option', () => {
271+
const buildApp = (encoding: 'gzip' | 'deflate') => {
272+
const app = new Hono()
273+
app.use('*', compress({ encoding }))
274+
app.get('/large', (c) => {
275+
c.header('Content-Type', 'text/plain')
276+
c.header('Content-Length', '1024')
277+
return c.text('a'.repeat(1024))
278+
})
279+
return app
280+
}
281+
282+
it('should compress when configured encoding is accepted by the client', async () => {
283+
const app = buildApp('gzip')
284+
const res = await app.request('/large', {
285+
headers: { 'Accept-Encoding': 'gzip' },
286+
})
287+
expect(res.headers.get('Content-Encoding')).toBe('gzip')
288+
})
289+
290+
it('should not compress when configured encoding is not in Accept-Encoding', async () => {
291+
const app = buildApp('gzip')
292+
const res = await app.request('/large', {
293+
headers: { 'Accept-Encoding': 'deflate' },
294+
})
295+
expect(res.headers.get('Content-Encoding')).toBeNull()
296+
})
297+
298+
it('should not compress when Accept-Encoding header is absent', async () => {
299+
const app = buildApp('gzip')
300+
const res = await app.request('/large')
301+
expect(res.headers.get('Content-Encoding')).toBeNull()
302+
})
303+
})
304+
305+
describe('Accept-Encoding parsing', () => {
306+
const buildAppDefault = () => {
307+
const app = new Hono()
308+
app.use('*', compress())
309+
app.get('/large', (c) => {
310+
c.header('Content-Type', 'text/plain')
311+
c.header('Content-Length', '1024')
312+
return c.text('a'.repeat(1024))
313+
})
314+
return app
315+
}
316+
317+
const buildAppWithEncoding = (encoding: 'gzip' | 'deflate') => {
318+
const app = new Hono()
319+
app.use('*', compress({ encoding }))
320+
app.get('/large', (c) => {
321+
c.header('Content-Type', 'text/plain')
322+
c.header('Content-Length', '1024')
323+
return c.text('a'.repeat(1024))
324+
})
325+
return app
326+
}
327+
328+
it('should not compress when configured encoding has q=0', async () => {
329+
const app = buildAppWithEncoding('gzip')
330+
const res = await app.request('/large', {
331+
headers: { 'Accept-Encoding': 'gzip;q=0' },
332+
})
333+
expect(res.headers.get('Content-Encoding')).toBeNull()
334+
})
335+
336+
it('should fall back to another encoding when the preferred one has q=0', async () => {
337+
const app = buildAppDefault()
338+
const res = await app.request('/large', {
339+
headers: { 'Accept-Encoding': 'gzip;q=0, deflate' },
340+
})
341+
expect(res.headers.get('Content-Encoding')).toBe('deflate')
342+
})
343+
344+
it('should compress when Accept-Encoding is the wildcard *', async () => {
345+
const app = buildAppWithEncoding('gzip')
346+
const res = await app.request('/large', {
347+
headers: { 'Accept-Encoding': '*' },
348+
})
349+
expect(res.headers.get('Content-Encoding')).toBe('gzip')
350+
})
351+
352+
it('should compress when Accept-Encoding token differs only in case', async () => {
353+
const app = buildAppWithEncoding('gzip')
354+
const res = await app.request('/large', {
355+
headers: { 'Accept-Encoding': 'GZIP' },
356+
})
357+
expect(res.headers.get('Content-Encoding')).toBe('gzip')
358+
})
359+
360+
it('should not treat x-gzip as gzip', async () => {
361+
const app = buildAppWithEncoding('gzip')
362+
const res = await app.request('/large', {
363+
headers: { 'Accept-Encoding': 'x-gzip' },
364+
})
365+
expect(res.headers.get('Content-Encoding')).toBeNull()
366+
})
367+
368+
it('should pick the encoding with the highest q value', async () => {
369+
const app = buildAppDefault()
370+
const res = await app.request('/large', {
371+
headers: { 'Accept-Encoding': 'gzip;q=0.5, deflate;q=0.9' },
372+
})
373+
expect(res.headers.get('Content-Encoding')).toBe('deflate')
374+
})
375+
376+
it('should prefer gzip over deflate when q values are equal', async () => {
377+
const app = buildAppDefault()
378+
const res = await app.request('/large', {
379+
headers: { 'Accept-Encoding': 'gzip;q=0.5, deflate;q=0.5' },
380+
})
381+
expect(res.headers.get('Content-Encoding')).toBe('gzip')
382+
})
383+
})
269384
})
270385

271386
async function decompressResponse(res: Response): Promise<string> {

‎src/middleware/compress/index.ts‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,40 @@
44
*/
55

66
import type { MiddlewareHandler } from '../../types'
7+
import { parseAccept } from '../../utils/accept'
78
import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'
89

910
const ENCODING_TYPES = ['gzip', 'deflate'] as const
11+
type Encoding = (typeof ENCODING_TYPES)[number]
1012
const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i
1113

1214
interface CompressionOptions {
13-
encoding?: (typeof ENCODING_TYPES)[number]
15+
encoding?: Encoding
1416
threshold?: number
1517
}
1618

19+
const selectEncoding = (
20+
header: string | undefined,
21+
candidates: readonly Encoding[]
22+
): Encoding | undefined => {
23+
if (header === undefined) {
24+
return undefined
25+
}
26+
const accepts = parseAccept(header)
27+
const wildcardQ = accepts.find((a) => a.type === '*')?.q
28+
let best: { encoding: Encoding; q: number } | undefined
29+
for (const enc of candidates) {
30+
const explicit = accepts.find((a) => a.type.toLowerCase() === enc)
31+
const q = explicit ? explicit.q : (wildcardQ ?? 0)
32+
if (q === 1) {
33+
return enc
34+
} else if (q > 0 && (!best || q > best.q)) {
35+
best = { encoding: enc, q }
36+
}
37+
}
38+
return best?.encoding
39+
}
40+
1741
/**
1842
* Compress Middleware for Hono.
1943
*
@@ -33,6 +57,7 @@ interface CompressionOptions {
3357
*/
3458
export const compress = (options?: CompressionOptions): MiddlewareHandler => {
3559
const threshold = options?.threshold ?? 1024
60+
const candidates: readonly Encoding[] = options?.encoding ? [options.encoding] : ENCODING_TYPES
3661

3762
return async function compress(ctx, next) {
3863
await next()
@@ -52,8 +77,7 @@ export const compress = (options?: CompressionOptions): MiddlewareHandler => {
5277
}
5378

5479
const accepted = ctx.req.header('Accept-Encoding')
55-
const encoding =
56-
options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))
80+
const encoding = selectEncoding(accepted, candidates)
5781
if (!encoding || !ctx.res.body) {
5882
return
5983
}

0 commit comments

Comments
 (0)