hono icon indicating copy to clipboard operation
hono copied to clipboard

`compress` middleware gzips images

Open jazoom opened this issue 1 year ago • 6 comments

What version of Hono are you using?

4.5.5

What runtime/platform is your app running on?

Bun

What steps can reproduce the bug?

Use the middleware as intended

app.use(compress())

What is the expected behavior?

Only compress response types that benefit from compression.

What do you see instead?

Images and other non-compressible types are gzip encoded. This wastes CPU for no reason, and often actually results in larger response sizes.

Additional information

No response

jazoom avatar Aug 12 '24 01:08 jazoom

Perhaps the middleware needs something along these lines?

        const contentType = c.res.headers.get("Content-Type");
	if (!contentType) {
		return;
	}

	const isCompressible =
		contentType.includes("text/") ||
		contentType.includes("application/json") ||
		contentType.includes("application/javascript") ||
		contentType.includes("application/xml");

	if (!isCompressible) {
		return;
	}

jazoom avatar Aug 12 '24 01:08 jazoom

It might also be worth having a content size below which compression is not applied.

jazoom avatar Aug 12 '24 01:08 jazoom

How about specifying the Content-Type for compression in the middleware options?

interface CompressionOptions {
  encoding?: (typeof ENCODING_TYPES)[number],
  contentType?: Array<string>
}

akku1139 avatar Aug 17 '24 16:08 akku1139

Cloudflare has a list here which may be a good default

https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression

jazoom avatar Aug 17 '24 20:08 jazoom

Being able to set it as an option also sounds like a great idea.

jazoom avatar Aug 17 '24 20:08 jazoom

Hi @jazoom @akku1139

This is an interesting issue. We can consider the API and implementation. Anyway, it's an enhancement rather than not a bug. I've changed the label.

yusukebe avatar Aug 18 '24 00:08 yusukebe

Now, we can close this issue. Thanks.

yusukebe avatar Sep 29 '24 10:09 yusukebe