Enabling GZIP Compression on a Phoenix Application

Posted by in Phoenix, last updated on 27 August, 2020

The issue

The other day I ran my blog through GTmetrix website speed test and realised that I had turned on GZIP compression for static assets, but not for dynamic content. This is easily fixed however with 2 lines of code:

Enabling GZIP compression for static assets

To enable compression for static assets add gzip: true (or gzip: Mix.env == :prod for production only) to the Plug.Static config in lib/your_app_web/endpoint.ex:

plug Plug.Static,
  at: "/",
  from: :your_app,
  gzip: Mix.env == :prod, # enable in production only
  only: ~w(css fonts images js...)

Enabling GZIP compression for dynamic content

To enable compression for dynamic content add compress: true to the Endpoint config in config/prod.secrets.exs:

config :your_app, YourAppWeb.Endpoint,
  http: [
    port: 4000,
    compress: true,
    transport_options: [socket_ops: [:inet6]]
  secret_key_base: System.get_env("SECRET_KEY_BASE")

With those changes you should be good to go!

Daniel Wachtel

Written by Daniel Wachtel

Daniel is a Full Stack Engineer who outside work hours is usually found working on side projects or blogging about the Software Engineering world.