I am building an ReactJs application that has many profiles.
The application will run in a development environment, qa environment and a production environment.
Given this, I would like to set on the host machine some environment variables and be able to get this on the .env file.
My need is to do something like:
.env file
REACT_APP_BASE_SERVICEX_URL=${ENV_ON_HOST_BASE_SERVICEX_URL}
REACT_APP_BASE_SERVICEY_URL=${ENV_ON_HOST_BASE_SERVICEY_URL}
Is this possible?
PS: The application will be running in Kubernetes.
.env file
REACT_APP_BASE_SERVICEX_URL=HOST_BASE_SERVICEX_URL
And where you want to use the env variable, use this in the following way -
const URL = process.env.REACT_APP_BASE_SERVICEX_URL
1- Install env-cmd package from npm
2- Make a file called .env.envName in your project root, sush as .env.staging, .env.production, ... to differentiate between variables in each environment.
3- Inside the env file add your variables in key/value representation with prefix of REACT_APP
4- Inside your package.json. change the scripts builds.
"scripts": {
"start": "env-cmd -f .env.staging react-scripts start",
"build:staging": "env-cmd -f .env.staging react-scripts build",
"build:production": "env-cmd -f .env.production react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
5- -f flag is for custom env file paths as the default is in the project root otherwise you should specify the actual path
"start": "env-cmd -f ../../.env.staging react-scripts start",
Are you just asking how to handle environment variables?
You can put any variables that you need in the .env, .env.local, .env.development or .env.production file and then copy them over to the .env file when deploying.
It is custom to fully capitalize variables within the .env file. To use them within the code you place process.env prior to it.
In .env file :
DB_URL = http://fwohfjiowjfwefjpw
In react :
const DBURL = process.env.DB_URL