LogoPly
Middleware

Compress

Brotli and gzip response compression.

Compress

middleware.Compress compresses response bodies when the client supports Brotli or gzip.

app.Use(middleware.Compress(0))

0 selects fasthttp's default compression level (6). Pass a level from 1 to 9 for gzip, or an appropriate Brotli level when Brotli is negotiated.

How it works

The middleware calls the next handler, then inspects the response. It skips compression when:

  • the handler aborted the chain,
  • the response uses a body stream,
  • the status is below 200, 204, or 304,
  • Content-Encoding is already set,
  • the body is shorter than 32 bytes,
  • the content type is not compressible.

When compression runs, Brotli is preferred if the request accepts it. Gzip is the fallback. The middleware sets Content-Encoding and Vary: Accept-Encoding, then removes Content-Length.

Compressible types

Compression applies to text/* and these application types:

  • JSON and JSON-based formats, including application/ld+json
  • JavaScript
  • XML and RSS/Atom
  • SVG
  • WOFF and TTF fonts

Images such as PNG, JPEG, and WebP are not compressed again.

Ordering

Compression wraps the response, so it should run after middleware that may set response headers or produce the final body:

app.Use(
	middleware.RequestID(),
	middleware.Logger(),
	middleware.Compress(0),
)

Avoid compressing already compressed payloads. The middleware checks Content-Encoding for this reason, but handlers should not set it unless the body is actually encoded.

When not to use it

  • Streaming responses such as SSE use a body stream and are skipped.
  • Very small responses gain nothing and are skipped.
  • If a proxy already compresses responses, disable this middleware to avoid duplicate work.