Serving Additional Static Assets in a Phoenix Application

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

Written by Ben Barber

A software engineer and data-driven trader from Cambridge, UK. Currently working full-time on developing trading algorithms for the US equity and options markets.

Don't miss the next post!

Subscribe to get future posts via email

Add your email address below to get notified when I publish new posts.

No spam ever. Unsubscribe anytime.