How to Handle Multiple Environments in a React App
Set up your React app for environments beyond development and production
When developing a React web application, developers can only use two environments by default.
- Development —
NODE_ENV=development
when developing the application locally. Uses.env.development
by default, if available. - Production —
NODE_ENV=production
when building the application for deployment. Uses.env.production
by default, if available.
When we use create-react-app, the package.json
has the following scripts:
"scripts": {
"start": "react-scripts start", // NODE_ENV=development as default
"build": "react-scripts build", // NODE_ENV=production as default
}
Imagine my project has four environments:
- Development
- Testing
- Staging
- Production
But, react-scripts only supports development and production.
Now, I want testing and staging environments. We cannot alter the value of NODE_ENV
, it can only be “development” or “production”.
So, we use an npm package env-cmd
. It is available at the link below.
The above npm package helps the user to change the env
variables based on the environments. To do so, execute the following steps.
1. Install env-cmd
npm Package
npm install env-cmd --save
Add env
files according to the environments and a .env
file with the common variables.
2. Define Environment Files
.env
REACT_APP_NAME = "Rockin MAT"
.env.development
REACT_APP_API_ENDPOINT = "https://api-dev.endpoint.com/"
.env.testing
REACT_APP_API_ENDPOINT = "https://api-testing.endpoint.com/"
.env.staging
REACT_APP_API_ENDPOINT = "https://api-staging.endpoint.com/"
.env.production
REACT_APP_API_ENDPOINT = "https://api.endpoint.com/"
Note: Prefix “REACT_APP_”
is required for creating custom variables in React.
3. Add Scripts to package.json
To test your work, run the following commands.
For the testing environment:
npm run build:testing
For the staging environment:
npm run build:staging
Note: Even though you are adding two new different environments when you build the app, NODE_ENV
will be production. To distinguish the builds, I recommend that you add REACT_APP_ENV
and specify your environment there.
Hooray! Now you can add more than two environments to your React code.