Building and deploying a Nodejs/React app as a static site on Heroku

  • react
  • coding
  • heroku

Alright so deploying some regular single page application (SPA) on Heroku is pretty much straightforward: your package.json probably has a build script already which does the usual compilation dance. And it probably also has a start script which will run whatever server-side renderer you're stuck with (i hear you, next.js).

But what if you just want to host the build as a static bundle? What if you're package.json doesn't have that start command for serving your production files?

Turns out, Heroku doesn't like static websites by default. But googling heroku deploy static site leads to the static buildpack sooner or later.

In the Deploy section it tells you to add heroku-community/static as a build-pack. But if you're, like me, skimming through the documentation site too fast and add this as heroku/heroku-buildpack-static to your app.json: joke's on you, it doesn't work.

Now you have the static server working but ... you are just getting a 404. Of course you have to build your app before you try to server the static files. But heroku-communtiy/static is just a static webserver, it won't run any build for you.

To make a long story short: add heroku/nodejs as a second buildpack to your app.json. Actually make it the first buildpack, otherwise Heroku will fail your build. Seems like the last buildpack in the list is responsible for actually binding to the expected port. And that should be your static webserver from heroku-community/static. Oh, and remove the start script from package.json if you have one ...

tl;dr: create app.json as follows:

{
"buildpacks": [
{ "url": "heroku/nodejs" },
{ "url": "heroku-community/static" }
]
}

Also don't forget to add static.json. git push and enjoy.