How to set ENV var in Heroku preview app postdeploy script How to set ENV var in Heroku preview app postdeploy script heroku heroku

How to set ENV var in Heroku preview app postdeploy script


Worked out with the assistance of Heroku's awesome support team a few years ago. We needed to set a reflexive environment variable for a middleware (parse-server) to know what to connect to. It's set manually on our Staging and Production apps, but to get it set on our review apps:

My app.json incldues:

  "scripts": {    "postdeploy": "bin/bootstrap"  },...  "env": {    "HEROKU_APP_NAME": {      "required": true    },    "HEROKU_PARENT_APP_NAME": {      "required": true    },...

bin/bootstrap is:

#!/usr/bin/env bashecho $HEROKU_APP_NAMEexport SERVER_URL=https://$HEROKU_APP_NAME.herokuapp.com/parse

SERVER_URL is available (and correct) in my review apps. It's been 👍no problems since we implemented.


I found this post which suggests that you can use the Heroku PlatformAPI.

In this case as a Rails Rake task which is run as the postdeploy:

desc 'Bootstrap review app'task bootstrap: ['db:schema:load', 'db:seed'] do  heroku = PlatformAPI.connect_oauth(ENV['HEROKU_API_TOKEN'])  heroku.config_var.update(ENV['HEROKU_APP_NAME'], 'WWW_HOSTNAME' => "#{ENV['HEROKU_APP_NAME']}.herokuapp.com")end


Take a look at the documentation for review apps https://devcenter.heroku.com/articles/github-integration-review-apps#heroku_app_name-and-heroku_parent_app_name

As long as you declare HEROKU_APP_NAME or HEROKU_PARENT_APP_NAME as required or optional in your app.json file, they will be available for you to use in your postdeploy script so you can just do:

HOST="$HEROKU_APP_NAME.herokuapp.com"