Sitemap
Dean Tedesco

Dean Tedesco

API Developer

Javascript: Dynamic Environments

2 min readApr 16, 2019

--

The Problem

When building your create-react-app for production deployments you currently need to bake in any environment variables at build time. This method of building your application can cause some issues particularly if you have many environments/stages in your deployment processes as you have to build for each one.

Get Dean Tedesco’s stories in your inbox

Join Medium for free to get updates from this writer.

Some issues for example are:

  • You can’t build once and deploy everywhere
  • If you need to change your environment after deployment for any reason you have to perform another build
  • Your environment is controlled by your build as opposed to your runtime

Some cons to this approach:

  • You must make sure you have all the correct environment variables set up on your deployment systems available otherwise your built apps will fail
  • Maintaining your application’s environment falls into the domain of DevOps

The Solution

Convert any process.env.* calls in your code to window._env_.* to access your environment at boot time instead of converting them at build time.

NOTE: this will not help you if you are deploying your built application on a CDN where you can’t set environment variables.

To help achieve this goal I’ve just published a new NPM package which we are going to start using at my work and you can find it at https://www.npmjs.com/package/@ethical-jobs/dynamic-env.

I’d love any feedback and/or pull requests as I think this could be very useful for many developers out there.

Github Repo: https://github.com/ethical-jobs/dynamic-env

Kudos

I also have to give kudos to Krunoslav Banovac for his inspiration as this package was based on his blog article https://medium.freecodecamp.org/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70.

--

--