React environment variables for a specific branch using .env

David Provan
2 min readJun 14, 2020

On a recent project we wanted to implement .env files to help with managing config values needed at build time. These variables weren’t keys or secrets but were still something we wanted to utilize to help keep config out our code base.

Naturally we turned to the dotenv library, I’ve used it on a few pet projects and found it’s simplicity a joy to use so felt comfortable it was perfect for our react project.

This was also my first time through using create-react-app for our react app set-up. In in reviewing the documentation I found they had support for .env files out of the box.

I was thrilled, I didn’t want to add more code and as long as we used the documented prefix REACT_APP_ in our variables we were set.

As I thought through and kept reading though I had a small hole that I wanted to document here in case anyone else needs the help. We have a set of specific environments and we wanted to be able to target .env values per environment. Create React App has some pretty good options for local development and production builds however we wanted to implement a specific .env file per branch.

At build time create react app will follow the precedence in the link above so will use .env.production for a “build” of the application. We needed to be able to set specific env files based on branch.

On our project each branch runs a build and the branch is targeting a given environment. So we created a .env.<environment> file and plopped it into the repo. Then I hoped into the CI/CD script and added a bash command that checked the branch and copied the appropriate source .env.<environment> file to .env

This worked great for us and wanted to share in case anyone else finds it useful!

--

--