February 11, 2020

Deploy a static middleman site on Heroku

You are using Heroku already? You need hosting for your static site you built using middleman?

Middleman is an awesome static site generator - I like to refer to it as static rails.
Heroku might already be your goto platform for hosting apps, so lets bring those two together.

Why middleman?

Middleman gives you a powerful asset pipeline, a huge number of plugins and enough good conventions to not keep you busy configuring things and instead get your static site out quickly.

Why heroku?

Now that you've finished your static website in no time, you need hosting. If you happen to already use heroku for other projects, it might be an easy and quick solution to host your static site as well.

How will this work?

You'll build your site with middleman like you are used to do or may already have.
Deployment will be done using Heroku CLI and git. There's a buildpack for Heroku we'll be using that enables serving a static site.

Build a site with middleman

Note, I'm using rbenv (with some plugins) to install ruby. I'm assuming you've a reasonably recent ruby & bundler installed already.

Install middleman and create your project:

gem install middleman
middleman init your-project-name

Configure and edit your site to your liking. I'm not going into details here, middleman has decent guides and/or you already know what you are doing.

Setup Heroku

Login to your Heroku account and create a new app. I'm calling mine "my-middleman-site". Then follow the instructions for installing the Heroku CLI on your machine:

heroku login

# change into your projects directory
cd your-project-name

git init
heroku git:remote -a my-middleman-site

We'll be using a Heroku buildpack called heroku-buildpack-static for making it serve our static site. This can be configured by running the following command:

heroku buildpacks:set https://github.com/heroku/heroku-buildpack-static.git

Configure for deployment

Out of the box middleman comes with a pre-configured .gitignore file to make sure the "build" directory, which is created when you runmiddleman buildand contains your site's static code is not commited to your git repository. That usually makes sense, because you can always recreate it, but we want to deliver that static code to Heroku using git, so we need to make sure it gets included.

Open your project's .gitignore file and remove the line that says build/:

.bundle
.cache
.DS_Store
.sass-cache
.gitignore

Create a file called static.json in the projects root directory:

{
  "root": "build/"
}
static.json

This file configures the buildpack and tells it that our site's static sources are in the build directory.

Deployment

Now we can manually test the deployment:

# build our site
middleman build

# deploy it to heroku
git add .
git commit -am "initial commit"
git push heroku master

At this point the site should be live and kicking.