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:

REACT_APP_API_BASE_URL=https://dev.example.com

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=https://int.example.com 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:

staging:
branch: staging
commands:
- REACT_APP_API_BASE_URL=https://staging.example.com 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.