Enhancing Your React Application with Environment Variables
API endpoints, feature toggles, anything that differs between your laptop and production. Here’s how environment variables handle it in React, and the one gotcha that catches people out.
Firstly, let’s understand what environment variables are: They are dynamic-named values that can affect the way running processes behave on a computer. For a React application, these can be set up in a .env file at the root of your project.
Start by creating a .env file at the root of your React project:
| |
Important: The REACT_APP_ prefix is mandatory for our Create React App to recognize our custom environment variables. Without this prefix, our variables would be ignored.
Next, you can access these environment variables anywhere in your React code using process.env. For instance, you might want to display the app name on your homepage component:
| |
Or, perhaps you need to use the API URL in a service to fetch some data:
| |
This method makes it easy to maintain different sets of configurations for different environments (development, staging, production, etc.) by simply switching out the .env file. For instance, you might have a .env.development for local development and a .env.production for your live site.
Just remember not to commit these .env files to your git repository, especially if they contain sensitive data. Instead, add .env to your .gitignore file and provide means for other developers or systems to create their own, such as a .env.example file with dummy data.
One warning worth repeating: every REACT_APP_ variable is baked into the bundle at build time and is readable by anyone who opens devtools. It’s configuration, not secrets. Put a key in there and you’ve published it.
