1

My react app is running on http://localhost:3000 and I wanted to setup the env variable for the different environment development, production, staging and local.

my react app url for different environment are(I am mocking my urls)

local = http://localhost:3000
development = http://react.developmet.com
production = http://react.production.com
stage = http://react.stage.com

looking for a solution how i can setup the env var for different environment.

Adding my approach to the same thing just wanted to know is this approach is good or not.

and how I can achieve same for staging environment

I have created an environment.js file.

let BASE_URL = http://localhost:3000

//check for environment
if (process.env.REACT_APP_ENV = "development") {
  BASE_URL = "http://react.developmet.com"
}
if (process.env.REACT_APP_ENV = "production") {
  BASE_URL = "http://react.production.com"
}

export {BASE_URL}

and also updated my run scripts

"scripts": {
     "dev":"REACT_APP_ENV=development npm start",
     "prod":"REACT_APP_ENV=productionnpm start",
     "build:dev":"REACT_APP_ENV=development npm run-script build",
     "build:prod":"REACT_APP_ENV=production npm run-script build",
    }

Rambo check
  • 33
  • 1
  • 6

1 Answers1

4

You can use env-cmd to manage your build for multiple env files:

Installation:

yarn add env-cmd -D

Create env files

  1. Create a folder envs at root project level
  2. Create .env files (as many as you need)

e.g. envs/.env.dev, envs/.env.prod, envs/.env.staging etc

A Sample .env (e.g. envs/.env.prod) file

REACT_APP_API_HOST=http://my-prod-api.example.com
REACT_APP_ANY_OTHER_VAR=some_value

Configure scripts in package.json file:

"scripts": {
    "start": "react-scripts start",
    "eject": "react-scripts eject",
    "dev": "env-cmd -f envs/.env.dev react-scripts build",
    "prod": "env-cmd -f envs/.env.prod react-scripts build",
    "staging": "env-cmd -f envs/.env.staging react-scripts build",
  },

Make the build:

$ yarn dev // to make build for dev env
$ yarn prod // to make build for prod env
$ yarn staging // to make build for staging env

PS: You can use npm commands as well. I used yarn only for example purpose.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
  • inside .env.dev file do i need to pass url like REACT_APP_DEV = http://react.developmet.com ? – Rambo check Feb 25 '21 at 09:10
  • Yes, please check my updated answer. I added a sample `.env` file. You can put your env vars in the file. – Ajeet Shah Feb 25 '21 at 09:13
  • when i am making a build for dev usnig npm run build:dev this is returning me the production enviroment(in the porcess.env,.NODE_ENV) so, i am getting my dev url as undefined when i am consoling it – Rambo check Mar 01 '21 at 06:57