Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 59 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

✔️  **h3 v1 & v2:** Works with both [h3](https://h3.dev) v1 and v2

✔️  **Nuxt module:** Drop `h3-compression/nuxt` into `nuxt.config` and configure it there



## Install
Expand Down Expand Up @@ -148,13 +150,62 @@ app.use(compression({ zstd: isZstdSupported() }))

## Nuxt 3 & 4

If you want to use it in Nuxt you can define a nitro plugin.
Add the module and you're done — it wires the right Nitro hooks, skips Nuxt's internal
routes and filters by content type for you:

```ts
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['h3-compression/nuxt'],
})
```

Everything is configurable under the `compression` key:

```ts
export default defineNuxtConfig({
modules: ['h3-compression/nuxt'],
compression: {
enabled: true,
encoding: 'zlib', // or 'stream'
brotli: false, // stream path only — zlib always prefers brotli
zstd: false, // needs Node >= 22.15
method: undefined, // force one method instead of negotiating
contentTypes: ['text/', 'application/json', 'application/javascript', 'application/xml', 'image/svg+xml'],
exclude: ['/_nuxt', '/__nuxt'],
routeRules: true, // also compress cached (swr/isr) routes and /server/api
threshold: 0, // skip bodies smaller than this many bytes
},
})
```

| Option | Default | What it does |
| --- | --- | --- |
| `enabled` | `true` | Turn compression off without removing the module |
| `encoding` | `'zlib'` | `'zlib'` buffers the body; `'stream'` pipes it through a compression transform |
| `brotli` | `false` | Consider brotli when negotiating. Only meaningful for `'stream'` — the zlib path already prefers brotli |
| `zstd` | `false` | Consider zstd when negotiating. Ignored on Node < 22.15, see [Zstd](#zstd) |
| `method` | – | Force one method instead of negotiating from `Accept-Encoding` |
| `contentTypes` | text, JSON, JS, XML, SVG | Prefix match against `Content-Type`. Set to `[]` to compress everything |
| `exclude` | `['/_nuxt', '/__nuxt']` | Path prefixes to skip. Compressing these breaks Nuxt's error page |
| `routeRules` | `true` | Also attach to `beforeResponse`, which is what cached (`swr`/`isr`) routes and `/server/api` handlers go through |
| `threshold` | `0` | Skip bodies below this size — under roughly a kilobyte compression makes payloads *larger*. Ignored for `'stream'`, where the size is not known up front |

> [!NOTE]
> `contentTypes` and `exclude` **replace** the defaults rather than extending them.
> Spread the defaults in if you want to add to them.

### Doing it manually

The module is a convenience wrapper — the hooks are still yours to wire if you want
different behaviour per route:

`server/plugins/compression.ts`
````ts
import { useCompression } from 'h3-compression'

export default defineNitroPlugin((nitro) => {
// Freshly rendered SSR pages.
nitro.hooks.hook('render:response', async (response, { event }) => {
// Skip internal nuxt routes (e.g. error page)
if (['/_nuxt', '/__nuxt'].some(prefix => getRequestURL(event).pathname.startsWith(prefix)))
Expand All @@ -165,24 +216,11 @@ export default defineNitroPlugin((nitro) => {

await useCompression(event, response)
})
})
````
> [!NOTE]
> `useCompressionStream` doesn't work right now in nitro. So you just can use `useCompression`

### Cached routes (SWR / ISR) and `/server/api`

The `render:response` hook only runs for freshly rendered SSR pages. Responses served
from the Nitro route cache (`routeRules` with `swr` / `isr`) and `/server/api` handlers
go through the `beforeResponse` hook instead. Use it to compress those too:

`server/plugins/compression.ts`
````ts
import { useCompression } from 'h3-compression'

export default defineNitroPlugin((nitro) => {
// The `render:response` hook only runs for freshly rendered SSR pages.
// Responses served from the Nitro route cache (`routeRules` with `swr` / `isr`)
// and `/server/api` handlers go through `beforeResponse` instead.
nitro.hooks.hook('beforeResponse', async (event, response) => {
// Skip internal nuxt routes (e.g. error page)
if (['/_nuxt', '/__nuxt'].some(prefix => event.path.startsWith(prefix)))
return

Expand Down Expand Up @@ -224,6 +262,10 @@ H3-compression has a concept of composable utilities that accept `event` (from `
- `compressResponseStream(event, value, method?, options?)` &nbsp;– low-level stream helper returning a compressed `Response`
- `isZstdSupported()` &nbsp;– whether the runtime can compress with zstd

#### Nuxt

- `h3-compression/nuxt` &nbsp;– the Nuxt module, configured under the `compression` key

## Sponsors

<p align="center">
Expand Down
13 changes: 13 additions & 0 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,20 @@ import { defineBuildConfig } from 'unbuild'
export default defineBuildConfig({
entries: [
'src/index',
'src/nuxt',
// The nitro plugin is consumed by the generated file the module writes into
// the Nuxt build dir, so it has to stay a resolvable file on disk rather
// than being rolled into the `nuxt` bundle.
{
input: 'src/runtime/',
outDir: 'dist/runtime',
builder: 'mkdist',
format: 'esm',
ext: 'mjs',
declaration: true,
},
],
externals: ['@nuxt/kit', '@nuxt/schema', 'h3', 'h3-compression'],
declaration: true,
clean: true,
rollup: {
Expand Down
20 changes: 19 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,17 @@
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"./nuxt": {
"types": "./dist/nuxt.d.ts",
"import": "./dist/nuxt.mjs",
"require": "./dist/nuxt.cjs"
},
"./nuxt-runtime": {
"types": "./dist/runtime/nitro-plugin.d.ts",
"import": "./dist/runtime/nitro-plugin.mjs"
},
"./package.json": "./package.json"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
Expand Down Expand Up @@ -64,12 +74,20 @@
"prepare": "simple-git-hooks"
},
"peerDependencies": {
"@nuxt/kit": "^3.0.0 || ^4.0.0",
"h3": "^1.6.0 || ^2.0.0"
},
"peerDependenciesMeta": {
"@nuxt/kit": {
"optional": true
}
},
"devDependencies": {
"@antfu/eslint-config": "^0.41.0",
"@antfu/ni": "^0.21.6",
"@antfu/utils": "^0.7.6",
"@nuxt/kit": "^3.13.0",
"@nuxt/schema": "3.21.11",
"@types/node": "^22.20.1",
"@types/supertest": "^2.0.12",
"@vitest/coverage-v8": "^0.34.3",
Expand Down
15 changes: 15 additions & 0 deletions playground/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,18 @@ yarn preview
```

Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.

## Note on h3 versions

Nuxt 3 runs on Nitro 2, which uses **h3 v1**. Because the workspace symlinks
`h3-compression` to the repo root, it resolves `h3` from the root's devDependency —
so build the playground with h3 v1 installed at the root, otherwise Nitro and
`h3-compression` end up with two different h3 majors in the same bundle:

```bash
pnpm add -D h3@^1.8.0 --ignore-scripts # in the repo root
pnpm build # rebuild dist/
cd playground && pnpm nuxt:prepare && pnpm build
```

This only affects the workspace. A real install resolves `h3` from the consuming app.
8 changes: 8 additions & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
devtools: { enabled: true },

modules: ['h3-compression/nuxt'],

compression: {
// Defaults shown for illustration — none of these are required.
encoding: 'zlib',
threshold: 1024,
},
})
5 changes: 4 additions & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
"nuxt:prepare": "nuxt prepare"
},
"dependencies": {
"h3-compression": "workspace:*"
},
"devDependencies": {
"@nuxt/devtools": "^0.8.2",
Expand Down
5 changes: 5 additions & 0 deletions playground/server/api/items.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// A `/server/api` route: goes through nitro's `beforeResponse` hook, not
// `render:response`. The module wires both, so this gets compressed too.
export default defineEventHandler(() => ({
items: Array.from({ length: 50 }, (_, i) => ({ id: i, name: `Item ${i}` })),
}))
10 changes: 0 additions & 10 deletions playground/server/plugins/compression.ts

This file was deleted.

Loading
Loading