Running your Ghost blog and Express app on Heroku

Running a Ghost blog as part of a website is a quite common scenario, and I was surprised when I encountered a problem when deploying to Heroku.

The problem was that, by default, Heroku gives you a single port in an environment variable process.env.PORT. If you're running, for example, Express app to serve your website and Ghost for your blog then you'll get an error that port is in use.

Custom build pack increases complexity and to maintain the site I should have good understanding of runit. It felt a bit overkill for the problem.

Several dynos would also increase complexity and makes maintenance cumbersome. I am not 100% sure how I would split my single repository to work differently on each application, I guess environment variables would be the solution. Overall this solution would be too complex.

I went with option three.

Ghost + Middleware

As I am writing this, using Ghost as a middleware is not yet officially supported. There are several discussions on a GitHub issues #4429 and #827. After investigating, I picked Mr. Josh Vanderwillik's solution and modified it slightly.

When a request comes to a blog, it will call function makeGhostMiddleware. Inside the function, it will start Ghost and also return the actual middleware that handles each request.

The request handler checks if Ghost isn't yet running then it will buffer the request to an array. When Ghost starts, it will go thru the array and process each individually. While the blogging platform is running buffering isn't needed, each requests Ghost processes immediately. Nice!

I hope this will help you get your site and blog running as a middleware!

Hi there! I'm Tatu, an independent Web developer; I help clients on building successful SaaS products. If you're interested in freelancing, you should check my email list How to get started as a freelancer. In my email list, I share private learnings from my own journey, including information about pricing, finding clients, working with the clients, how to get started, etc.
Please don't hesitate to reach out by sending an email or via Twitter.

Are you a Web Developer and been considering freelancing?

In my email list I share private learnings from my own journey, including information about pricing, finding clients, working with the clients, how to get started, etc. Sign up now to learn more + to personally ask me questions!