Simple Static Server with Elixir and Plug

Similar to Rack in Ruby, Plug seems to be the de-facto generic adapter for web servers in Elixir. Here’s are simple steps to get a simple static server running.

First let’s create a mix project:

> mix new server
> cd server

We can use some default Plug modules to help us with serving files, namely Plug.Router and Plug.Static.

First lets add in the dependencies in mix.exs:

defp deps do
  [{:cowboy, "~> 1.0.0"},
  {:plug, "~> 1.0"}]

Next, in lib/server.ex, fill in the module like so:

defmodule Server do
  use Plug.Router

  plug Plug.Static, at: "/", from: :server

  plug :match
  plug :dispatch

  get "/" do
    conn = put_resp_content_type(conn, "text/html")
    send_file(conn, 200, "priv/static/index.html")

  match _ do
    send_resp(conn, 404, "not found")


Plug.Static allows us to serve static files from some specified path on our server. Since we are passing in our app name as an atom, :server, by default the root URL will be mapped to priv/static/.

The :match and :dispatch plugs allow us to use the get and match functions. We use them here to route the root URL to serve an index file.
If the request path is not the root, then the match function will match all other requests to a 404 response.

Run the Plug app within iex:

$ iex -S mix
iex> c "lib/server.ex"
iex> {:ok, _} = Plug.Adapters.Cowboy.http Server, []

Go to localhost:4000 and voila, we have a simple, static server running with Plug!