Home > Back-end >  How to get environment variable from the host on react .env file
How to get environment variable from the host on react .env file

Time:08-27

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.

CodePudding user response:

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",

CodePudding user response:

Are you just asking enter image description here

And in my .env file:

enter image description here

Now I am able to get host's environment variables.

  • Related