How to serve gzipped assets through a CDN?

Hi,

I am trying to deploy a Phoenix application and everything seems quite straightforward. It loads with all the assets, except I am being stuck at the assets being loaded being the non-gzipped versions, which of course slows down things tremendously.

I am looking at making the following setup work: deploying a mix release to an AlpineJS server (works), uploading assets to a DigitalOcean Space with CDN enabled (works) and then making the application use those assets (works, but).

For that, my setup is as follows:
In config/releases.exs, I have added static_url: [scheme: "https", port: 443, host: "assets.example.dev", path: "/static"] to the ExampleWeb.Endpoint config.
For asset loading, in the root template layout, I have

<link
      phx-track-static
      rel="stylesheet"
      href="<%= Routes.static_url(@conn, "/css/app.css") %>"
    />
  <script
      defer
      phx-track-static
      type="module"
      src="<%= Routes.static_url(@conn, "/js/app.js") %>"
    ></script>

I run yarn deploy --cwd assets and mix phx.digest, which correctly builds all the assets into priv/static, attaches a hash and gzips each file. These files are then uploaded to the Space (S3 compatible). The created cache_manifest.json is then uploaded to the server.

Now, all of that works quite well and the correct assets are loaded properly, except that I would like it to load the .gz versions from the CDN. They are available and can be accessed, but Phoenix loads the larger, non-gzip ones. Setting gzip: true in the Static plug doesn’t change anything since the assets are obviously not served by the plug, but by a CDN.

Is there any way to make this work and have Phoenix access the gzip versions?

Cheers and have a great rest of your weekend!

1 Like

Hello and welcome,

In your endpoint.ex, You can set gzip to true. Maybe it can help You…

  # Serve at "/" the static files from "priv/static" directory.
  #
  # You should set gzip to true if you are running phx.digest
  # when deploying your static files in production.
  plug Plug.Static,
    at: "/",
    from: :your_app,
    gzip: true,
    only: ~w(css fonts images js favicon.ico robots.txt)
2 Likes

I didn’t have the exact issue but a similar one and it turned out that it was cache_manifest.json placement. Phoneix would serve regular files in every case that it fails to find cache_manifest.json. May be this gives you some help

1 Like