Serving Additional Static Assets in a Phoenix Application

April 21, 2018 ~ 1 min read

I recently had the requirement to serve some static files from within a Elixir Phoenix application but this was not as simple as dropping the files into a directory under priv/static.

Phoenix by default has the static paths set to a defined list of files and directories, therefore any non standard assets that we want to serve must be explicitly declared in the endpoint configuration.

The endpoint configuration can be found in /lib/<app-name>Web/endpoint.ex which if you look trough you will find the Plug used for adding static paths.

plug Plug.Static,
  at: "/",
  from: :my_phoenix_app,
  gzip: true,
  only: ~w(css fonts images js favicon.ico robots.txt)

For my use-case I needed the static files served from a /docs directory so I created a new directory priv/static/docs that contained the files and then added the path to the endpoint configuration like so.

plug Plug.Static,
  at: "/",
  from: :my_phoenix_app,
  gzip: true,
  only: ~w(css fonts images js favicon.ico robots.txt docs)

Then that was all there was to it, everything now worked perfectly.

Ben Barber

A software engineer specialising in the development of web applications using Elixir, Phoenix, Ruby on Rails and React. Find out more »

Join 423 other subscribers. No spam ever.