In this article we are going to learn how to configure multiple environments in a single React application. For example, you might want your dev environment connected to your dev API Endpoint, QA to QA endpoint and production to a production endpoint. We could solve this by using a single .env file but, each time you push your code to specific environments you need to remember to change the endpoint values, which is a slight headache and can be error prone. Let’s see how we can solve this!
First, get the package env-cmd from npm by running
npm install — save-dev env-cmd
Next, create your environment specific .env files. In this example, I’ve created a folder named “environments” in my root directory (same level as package.json). Important the environment variables MUST start with REACT_APP_ . Read more here.
Then, I’ve my .dev.env , .qa.env and .prod.env created inside environments folder.
REACT_APP_API_END_POINT==http://my-dev-url.com
//.dev.env
REACT_APP_API_END_POINT==http://my-qa-url.com
//.qa.env
REACT_APP_API_END_POINT==http://my-prod-url.com
//.prod.env
Please note .dev.env, .qa.env and .prod.env are three separate files in the environments folder. See below
Next, update the package.json . Update the scripts portion of your package.json to include the following:
“scripts”: {
“start”: “react-scripts start”,
“build”: “react-scripts build”,
“test”: “react-scripts test”,
“eject”: “react-scripts eject”,
“start:dev”: “env-cmd -f ./environments/.dev.env react-scripts start”,
“build:dev”: “env-cmd -f ./environments/.dev.env npm run-script build”,
“start:qa”: “env-cmd -f ./environments/.qa.env react-scripts start”,
“build:qa”: “env-cmd -f ./environments/.qa.env npm run-script build”,
“start:prod”: “env-cmd -f ./environments/.prod.env react-scripts start”,
“build:prod”: “env-cmd -f ./environments/.prod.env npm run-script build”
},
Next start your local/dev react application by running
npm run start:dev
You can test your env variable in your app by doing the following
console.log(process.env.REACT_APP_API_END_POINT);
For QA and Production build replace the command npm run build to the newly added environment specific command npm run build:qa or npm run build:prod respectively. (For example, if you are on AWS, edit the buildspec on Codebuild and replace npm run build with npm run build:qa or npm run build:prod)
Always use your judgement skills, and remember not add any sensitive information in those files.
And that’s it. We’ve learned how to create multiple environments in a react application using Create React App.
I hope this article was helpful. Thanks and Cheers!
Top comments (1)
You save me day :)