Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/gofiber/fiber/llms.txt

Use this file to discover all available pages before exploring further.

Compression middleware for Fiber that automatically compresses responses with gzip, deflate, brotli, or zstd based on the client’s Accept-Encoding header.
Bodies smaller than 200 bytes remain uncompressed because compression would likely increase their size and waste CPU cycles. See the fasthttp source.

Behavior

  • Skips compression for responses that already define Content-Encoding, for range requests, 206 responses, status codes without bodies, or when either side sends Cache-Control: no-transform
  • HEAD requests negotiate compression so Content-Encoding, Content-Length, ETag, and Vary reflect the encoded representation, but the body is removed before sending
  • When compression runs, strong ETag values are recomputed from the compressed bytes; when skipped, Accept-Encoding is still merged into Vary unless the header is * or already present

Signatures

func New(config ...Config) fiber.Handler

Usage

import (
    "github.com/gofiber/fiber/v3"
    "github.com/gofiber/fiber/v3/middleware/compress"
)

Basic Example

// Initialize default config
app.Use(compress.New())

// Or extend your config for customization
app.Use(compress.New(compress.Config{
    Level: compress.LevelBestSpeed, // 1
}))

Skip Specific Routes

app.Use(compress.New(compress.Config{
    Next:  func(c fiber.Ctx) bool {
      return c.Path() == "/dont_compress"
    },
    Level: compress.LevelBestSpeed,
}))

Configuration

Next
func(fiber.Ctx) bool
default:"nil"
Skips this middleware when the function returns true.
Level
Level
default:"LevelDefault (0)"
Compression level to use. Available levels:
  • LevelDisabled (-1): Compression is disabled
  • LevelDefault (0): Default compression level
  • LevelBestSpeed (1): Best compression speed
  • LevelBestCompression (2): Best compression

Default Config

var ConfigDefault = Config{
    Next:  nil,
    Level: LevelDefault,
}

Constants

// Compression levels
const (
    LevelDisabled        = -1
    LevelDefault         = 0
    LevelBestSpeed       = 1
    LevelBestCompression = 2
)

Common Use Cases

Maximum Compression for Static Assets

app.Use("/static", compress.New(compress.Config{
    Level: compress.LevelBestCompression,
}))

Fast Compression for API Responses

app.Use("/api", compress.New(compress.Config{
    Level: compress.LevelBestSpeed,
}))

Conditional Compression

app.Use(compress.New(compress.Config{
    Next: func(c fiber.Ctx) bool {
        // Don't compress images
        return strings.HasPrefix(c.Get("Content-Type"), "image/")
    },
}))

Selective Compression by Route

// Compress API responses
api := app.Group("/api")
api.Use(compress.New(compress.Config{
    Level: compress.LevelBestSpeed,
}))

// Don't compress file uploads
app.Post("/upload", uploadHandler) // No compression