StackTips
 4 minutes

How to Enable GZIP Compression in Spring Boot?

By Nilanchala @nilan, On Jan 28, 2024 Spring Boot 3.67K Views

HTTP compression is a capability that can be built into web servers and web clients to improve transfer speed and save bandwidth utilisation. The commonly used compression is GZIP.

By default, the gzip compression is disabled in the Spring Boot application. However, we can enable compression using a few property changes.

Enable GZIP Compression

Add the following configuration to your Spring Boot application.properties file to enable gzip response compression.

# Enable response compression
server.compression.enabled=true

# Mime types that should be compressed
server.compression.mime-types=text/xml, text/css, text/javascript, application/json

This configuration will enable the gzip compression for all responses for the given mime types defined in the property file.

💡
Please note, that the wildcard in mime types is not supported. So we need to provide the list of mime types explicitly.

The gzip operation consumes time and other server resources. You may enable the compression only when the response size exceeds a specific limit. This can be configured using the following property.

# Minimum response where compression will kick in
server.compression.min-response-size=4096

Exclude user agents from the compression

You can also exclude the specific user agents using excluded-user-agents configuration.

server.compression.excluded-user-agents= Mozilla/5.0

If you are using a YAML-based configuration, all the above properties can be written as follows:

server:
  compression:
    enabled: true
    mime-types: text/xml, text/css, text/javascript, application/json
    min-response-size: 1024
    excluded-user-agents: Mozilla/5.0
nilan avtar

Nilanchala

I'm a blogger, educator and a full stack developer. Mainly focused on Java, Spring and Micro-service architecture. I love to learn, code, make and break things.