$ cat docs/middleware/compress.md
CompressionCompressão
Compress response bodies with the standard CompressionStream, negotiating gzip or deflate from accept-encoding.Comprima corpos de resposta com o CompressionStream padrão, negociando gzip ou deflate a partir do accept-encoding.
What it doesO que faz
compress(options?: CompressOptions): MiddlewareHandler. Compresses with the standard
CompressionStream (gzip or deflate, negotiated from accept-encoding in server order) when
content-length is at least threshold bytes (default 1024) or, without
content-length, the type is textual (compressed as it streams, never buffered or measured) and
filter(ctx, response), when given, returns true. Sets content-encoding and vary: accept-encoding and
removes content-length.
compress(options?: CompressOptions): MiddlewareHandler. Comprime com o CompressionStream
padrão (gzip ou deflate, negociado pelo accept-encoding na ordem do servidor) quando o body tem pelo
menos threshold bytes (padrão 1024) pelo content-length ou, sem content-length,
o tipo é textual (comprimido enquanto flui, sem buffer nem medição), e o filter(ctx, response), quando
informado, devolve true. Define content-encoding e vary: accept-encoding e remove
content-length.
Install and orderInstalar e ordenar
pnpm add @tupik/middleware
Register it with .use(compress()) before the routes that return compressible bodies. It only wraps
downstream responses, so it can sit next to cors, rateLimit and logger in the same chain.
Registre com .use(compress()) antes das rotas que retornam corpos comprimíveis. Ele só envolve as
respostas seguintes, então pode ficar ao lado de cors, rateLimit e logger na mesma cadeia.
ExampleExemplo
import { compress } from '@tupik/middleware';
const rows = Array.from({ length: 500 }, (_, id) => ({ id, name: 'item-' + id }));
createModule()
.use(compress({
threshold: 1024,
encodings: ['gzip', 'deflate'],
// skip pages that mix a secret with reflected input (BREACH)
filter: (ctx) => !ctx.req.url.includes('/account'),
}))
.get('/report', { access: 'public', handler: (ctx) => ctx.json({ rows }) });
// accept-encoding: gzip → content-encoding: gzip, vary: accept-encoding, content-length removedimport { compress } from '@tupik/middleware';
const rows = Array.from({ length: 500 }, (_, id) => ({ id, name: 'item-' + id }));
createModule()
.use(compress({
threshold: 1024,
encodings: ['gzip', 'deflate'],
// pule páginas que misturam segredo com entrada refletida (BREACH)
filter: (ctx) => !ctx.req.url.includes('/account'),
}))
.get('/report', { access: 'public', handler: (ctx) => ctx.json({ rows }) });
// accept-encoding: gzip → content-encoding: gzip, vary: accept-encoding, content-length removed APIAPI
| TypeTipo | ShapeFormato |
|---|---|
CompressOptions | { threshold?: number; encodings?: readonly CompressEncoding[]; filter?: (ctx, response: Response) => boolean } |
CompressEncoding | 'gzip' | 'deflate' |
Errors and limitsErros e limites
- It skips 204/304 (and other bodyless or partial statuses), already encoded bodies,
text/event-stream, cache-control: no-transform and HEAD. - Compressing weakens a strong ETag: the middleware converts it to a weak tag, so caches and conditional requests still behave.
- Compression costs CPU per request; below the threshold (by
content-length) the body is passed through untouched. Textual bodies without content-length are always compressed. - Compressing a response that mixes a secret (CSRF token, session data) with attacker-controlled input exposes it to BREACH; turn those routes off with
filter.
- Ignora 204/304 (e outros status sem body ou parciais), bodies já codificados,
text/event-stream, cache-control: no-transform e HEAD. - Comprimir enfraquece um ETag forte: o middleware o converte em tag fraca, então caches e requisições condicionais continuam funcionando.
- Compressão custa CPU por requisição; abaixo do threshold (pelo
content-length) o body passa intacto. Bodies textuais sem content-length são sempre comprimidos. - Comprimir uma resposta que mistura segredo (token CSRF, dados de sessão) com entrada do atacante a expõe ao BREACH; desligue essas rotas com
filter.
When not to use itQuando não usar
Do not compress tiny responses, already compressed payloads or long-lived streams. If a CDN or reverse proxy
already compresses, adding it again only spends CPU without shrinking the transfer.
Não comprima respostas minúsculas, payloads já comprimidos ou streams de longa duração. Se um CDN ou proxy reverso
já comprime, adicionar de novo só gasta CPU sem reduzir a transferência.