Skip to main content

Import

import { compress } from 'hono/compress'

Usage

const app = new Hono()

app.use(compress())

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

Options

The compress middleware accepts an optional CompressionOptions object:
encoding
'gzip' | 'deflate'
The compression scheme to allow for response compression. If not defined, both gzip and deflate are allowed and will be used based on the Accept-Encoding header. gzip is prioritized if this option is not provided and the client accepts both.
threshold
number
default:1024
The minimum size in bytes to compress. Responses smaller than this threshold will not be compressed. Defaults to 1024 bytes (1KB).

Signature

compress(options?: CompressionOptions): MiddlewareHandler

Examples

Basic usage

const app = new Hono()

app.use(compress())

Force gzip compression

app.use(compress({ encoding: 'gzip' }))

Force deflate compression

app.use(compress({ encoding: 'deflate' }))

Custom threshold

// Only compress responses larger than 2KB
app.use(compress({ threshold: 2048 }))

Disable compression for small responses

// Only compress large responses (>10KB)
app.use(compress({ threshold: 10240 }))

Apply to specific routes

const app = new Hono()

// Compress only API responses
app.use('/api/*', compress())

app.get('/api/data', (c) => {
  return c.json({ data: largeDataset })
})

Behavior

  • Skips compression if:
    • Response already has Content-Encoding header
    • Response already has Transfer-Encoding header
    • Request method is HEAD
    • Content length is below threshold
    • Content type is not compressible
    • Response has Cache-Control: no-transform
  • Removes Content-Length header after compression (length changes)
  • Sets Content-Encoding header to the compression method used
  • Uses native CompressionStream API for compression
  • Automatically selects encoding based on Accept-Encoding header
  • Only compresses compressible content types (text/html, application/json, etc.)

Build docs developers (and LLMs) love