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=developmentwhen developing the application locally. Uses.env.developmentby default, if available. - Production —
NODE_ENV=productionwhen building the application for deployment. Uses.env.productionby 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 --saveAdd 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.





