When we create a react app we always develop two environment.
When we are doing development in multiple stages or we are having different domain names or servers.
In our local we are using https://server1.api/yourApiEndUrl but when we deploy it to production or staging we may need it to be https://server3.api/yourApiEndUrl.
To manage this situation we always try to push our code with server3 url and to run it we have to change this on local as server1 url. To solve this problem we use multiple environment variable
Imagine our project has three environments:
And we have different API URL for each environment which can use to run the project like.
We can add the .env file in root directory to manage all environment. Following are the files which we can use for different environments.
REACT_APP_BASE_API_URL = https://server1.api/yourApiEndUrl
REACT_APP_BASE_API_URL = https://server1.api/yourApiEndUrl
REACT_APP_BASE_API_URL = https://server1.api/yourApiEndUrl
Like
Now we need a library to change the environment according to server automaticaly called env-cmd
To install this library run
By using npm
npm i env-cmd or npm install env-cmd
By using yarn
yarn add env-cmd
After installing this library we need to change our build script in Package.json file in root directory like.
scripts: { "start": "react-scripts start", "build": "react-scripts build", "build:testing": "env-cmd -f .env.testing react-scripts build", // for local development and testing "build:staging": "env-cmd -f .env.staging react-scripts build", // for staging "build:production": "env-cmd -f .env.production react-scripts build", // for production ... },
To test your work, run the following commands as required.