Elixir: Serving Static Pages with Plug - [006]

Serving static pages is one of the basic things our application will need to do. We'll show you how to accomplish this with plug. This episode is for members only Become a member to get access.


We'll configure Plug.Static in lib/botiful.ex

defmodule Botiful do  use Plug.Router  plug Plug.Logger    plug Plug.Static,    at: "/",    from: {:botiful, "priv/static"},    only: ~w(index.html)      # ...end

The at: "/" option means that we can access the asset from root, which means we can simply pass localhost:8080/index.html into the browser and it will serve us the static page. If we changed the at: "/" option to at: "/public" we will need to append /public/index.html to our path.

Example HTML Content

We will need to put our static page inside the priv/static directory as obviated by the configuration above. Let's create our example html page at priv/static/index.html with the following content.

<html>  <head>    <title>It's a Botiful Day!</title>  </head>  <body>    Yay static page!  </body></html>

We should now be able to access our static page from localhost:8080/index.html

Root Page

We might want to access the page without specifying the file so localhost:8080/ should point to the root static page automatically. Let's see how we can set this up.

defmodule Botiful do  use Plug.Router  # ...    # Add the following  get "/" do    conn    |> put_resp_header("content-type", "text/html; charset=utf-8")    |> send_file(:ok, root())  end    defp root do    Enum.join([:code.priv_dir(:botiful), "/static/index.html"])  end    end

The root() private function simply returns the path to the index file. We then use the send_file function and call the root() function to get the path of the file we want to send. We have to be sure to set the content-type in the response header as well.

That should be enough for our application to serve static pages in our application. Later in the series we will see how this all works with the react application.