> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/honojs/hono/llms.txt
> Use this file to discover all available pages before exploring further.

# compress

> API reference for the Compress middleware

## Import

```typescript theme={null}
import { compress } from 'hono/compress'
```

## Usage

```typescript theme={null}
const app = new Hono()

app.use(compress())

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

## Options

The `compress` middleware accepts an optional `CompressionOptions` object:

<ParamField path="encoding" type="'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.
</ParamField>

<ParamField path="threshold" type="number" default={1024}>
  The minimum size in bytes to compress. Responses smaller than this threshold will not be compressed. Defaults to 1024 bytes (1KB).
</ParamField>

## Signature

```typescript theme={null}
compress(options?: CompressionOptions): MiddlewareHandler
```

## Examples

### Basic usage

```typescript theme={null}
const app = new Hono()

app.use(compress())
```

### Force gzip compression

```typescript theme={null}
app.use(compress({ encoding: 'gzip' }))
```

### Force deflate compression

```typescript theme={null}
app.use(compress({ encoding: 'deflate' }))
```

### Custom threshold

```typescript theme={null}
// Only compress responses larger than 2KB
app.use(compress({ threshold: 2048 }))
```

### Disable compression for small responses

```typescript theme={null}
// Only compress large responses (>10KB)
app.use(compress({ threshold: 10240 }))
```

### Apply to specific routes

```typescript theme={null}
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.)
