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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

inside .env.dev file do i need to pass url like REACT_APP_DEV = react.developmet.com ?
Yes, please check my updated answer. I added a sample .env file. You can put your env vars in the file.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.