7

I am attempting to figure out the best way to load environment variables into my AngularJS app. I am currently using constants, which take their valuues from those defined in the Webpack definePlugin. However, this causes an issue with Heroku as the code is built when pushed to staging, and when it is promoted to production, it is not rebuild, therefore the webpack definePlugin constants are the staging environment variables.

I have looked at requesting the environment variables from my API at run time and then setting them as constants to be used in my front-end, but I can't figure out how to set constants programatically outside of the initial .constant(..) opportunity.

If anyone knows any other better practices around loading environment variables into a front-end when using Webpack (and not Grunt) please do let me know.

1 Answer 1

1

If you are using node.js (and npm) in your server, you could consider running webpack in the "npm prestart" script, instead of in "npm postinstall".

That way webpack would run every time your heroku dynos start or recycle, and so would pick up your env var definitions from the appropriate Heroku pipeline phase. So, when your staging dynos start, webpack would pick up your staging env var definitions, and when your production dynos start, webpack would pick up your production env var definitions.

The disadvantage of this approach, however, is that increases the time your dynos are out of service while recycling, since they now need to run webpack before starting.

Sign up to request clarification or add additional context in comments.

3 Comments

Would this also happen if the app were to be randomly rebooted for some reason? This is a very clean option, but I'm unsure how dangerous it is.
With this option webpack would run every time npm start is run. So, on Heroku, that means every time the app recycles, or restarts for any other reason (such as when you change environment variables, promote from one pipeline app to another etc.).
However, as noted, this solution adds to the downtime of your dynos when recycling etc. You need to make sure that is not an issue for your app. There are ways to work around this, of course (e.g. see devcenter.heroku.com/articles/preboot), but you need to be aware of the implications.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.