Skip to main content
Module

x/hono/middleware/compress/index.ts

Ultrafast web framework for the Edge
Extremely Popular
Go to Latest
File
import type { MiddlewareHandler } from '../../types.ts'
type EncodingType = 'gzip' | 'deflate'
interface CompressionOptions { encoding?: EncodingType}
export const compress = (options?: CompressionOptions): MiddlewareHandler => { return async (ctx, next) => { await next() const accepted = ctx.req.headers.get('Accept-Encoding') const pattern = options?.encoding ?? /gzip|deflate/ const match = accepted?.match(pattern) if (!accepted || !match || !ctx.res.body) { return } const encoding = match[0] // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const stream = new CompressionStream(encoding as EncodingType) ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res) ctx.res.headers.set('Content-Encoding', encoding) }}