Search code examples
herokumonorepo

Using variables with heroku-buildpack-static


I have a monorepo containing, among other things, a React app. I'm using The create-react-app Buildpack, which uses heroku-buildpack-static to serve stuff.

Since the app is in foo/examples/bar, I've created the following static.json:

{
  "root": "foo/examples/${EXAMPLE}/build/",
  "routes": {
    "/**": "index.html"
  }
}

And an EXAMPLE config var with the value bar. According to the docs, this should work.

When the app is built by heroku, I see this in the log:

app[web.1]: nginx: [emerg] unknown "example" variable
app[web.1]: Process exited unexpectedly: nginx
app[web.1]: Going down, terminating child processes...
heroku[web.1]: State changed from starting to crashed
heroku[web.1]: Process exited with status 1

Is there a way to fix this build, or a better way to deploy this kind of repo?


Solution

  • So your main buildpack is create-react-app-buildpack.

    Which then uses 3 buildpacks as seen at create-react-app-buildpack

    https://github.com/heroku/heroku-buildpack-nodejs.git
    https://github.com/mars/create-react-app-inner-buildpack.git#v9.0.0
    https://github.com/heroku/heroku-buildpack-static.git
    

    The feature you are looking for is in the buildpack heroku-buildpack-static. If we look at the source code of the same

    There are only 3 variables which support interpolation, we can see the same at

    heroku-buildpack-static

    Now for us to get interpolation in root variable as well, we need to modify the code like

    json["root"] ||= DEFAULT[:root]
    json["root"] = NginxConfigUtil.interpolate(json["root"], ENV) if json["root"]
    

    So I forked the repo to update the same

    heroku-buildpack-static

    But since the buildpacks are defined in create-react-app-buildpack, so we need to fork that and update the .buildpacks file as done below

    create-react-app-buildpack

    Now after that we use this forked repo as our build pack

    $ heroku config:set  JS_RUNTIME_TARGET_BUNDLE="/app/packages/examples/grid/build/static/js/*.js"
    $ heroku buildpacks:set https://github.com/tarunlalwani/heroku-buildpack-static.git
    $ heroku config:set  EXAMPLE=grid
    $ heroku push origin master
    

    And now the build works fine

    Working fine