How do I serve static assets on the web with Elixir using Cowboy and Plug?

Last updated

This post is also available in different formats so you can read on the go or share it around!

As a web developer, serving static assets is essential. It may be images, JavaScript and CSS or even static HTML pages. Let’s take a look at how we could make a very basic web server that serves everything from a static assets folder.

What we’re making

We’re going to make server in Elixir using plug_cowboy that will serve the assets folder. This will be very simple and won’t do any routing, we’ll simply use the Plug.Static plug. Take a look at the source code in an example repo here.

How to make a static asset server

Let’s start from scratch and create a new project, if you’ve got an existing project there’s only a couple changes to make so you can use this as a guide.

Create a new project

Run mix new simple_plug_static --sup to setup the project then add plug_cowboy to your dependencies in mix.exs

Your mix.exs deps function should look like this:

defp deps do
  [
    {:plug_cowboy, "~> 2.5"}
  ]
end

You can update the dependencies afterwards by running mix deps.get.

Use Plug.Cowboy

The only other step is to update lib/simple_plug_static/application.ex.

Update the children variable to setup a Plug.Cowboy.

children = [
  {Plug.Cowboy, scheme: :http, plug: {Plug.Static, at: "/", from: "assets"}, options: [port: 3000]}
]

The key part is using Plug.Static and providing a couple of options.

  • at specifies the path that’s accessible on the server
  • from specifics the directory to serve, in our case let’s set this to assets

Create some assets to serve

Create the following folder simple_plug_static/assets and put some files you want to serve. In the example, I created hello.txt but other files should work just the same.

Start the server and try it out

Start the server with mix run --no-halt, once it’s up and running you should be able to visit localhost:3000/hello.txt in a browser to access the static resources.

That’s it.

When to use this

This is a very simple static asset server with almost no configuration. In a real world scenario, it’s more common to use a router and serve static assets as part of a larger application.

Resources

Seth Corker

A Fullstack Software Engineer working with React and Django. My main focus is JavaScript specialising in frontend UI with React. I like to explore different frameworks and technologies in my spare time. Learning languages (programming and real life) is a blast.