How to work around create react apps .env files if your environment is not development, test or production

Create React app is a great tool to use when developing react applications. Pre 1.0, you were given a .env file to have environment variables in your application to use in your components and html. 1.0 brought new features, adding the ability to have .local.development , etc files to override based on what environment the app was being built on. This is a good default setup! If you’re setup differs from these names, and you have some needs to point to different urls based on environment, you may need a workaround depending on your requirements.

The underlying package used by create react app is dotenv.

This package will not overwrite an environment variable if it is already defined on the system it’s being used on.

For this example, let’s say we have some base urls that differ by environment, crazy right? You could write some code to parse the url, add some conditionals, but why?

In your .env file, let’s say you have this:


but you have an integration environment, where NODE_ENV is equal to production to compile the code correctly but you want a slightly different value for the base url.

In unix based systems, you can declare the environment variable alongside the build command to define it for that command!

REACT_APP_API_BASE_URL= yarn run build

Problem solved. If your’e using a CI to deploy your code, most setups have a branch based configuration option, where you can add things:

branch: staging
- REACT_APP_API_BASE_URL= yarn run build

Happy environment variables, happy app!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.