I have such a question, I'm trying to figure out how to start a react application (created through create-react-app) with different profiles. That is, suppose I have several environments (local, dev, prod) and I have a fetch that refers to the backend (which is deployed on another server). And the backend has its own address for each environment. That is, I need to somehow set the globally variable that I give to fetch and everything will work. for example, in Springboot this can be done through the application- "profile". properties. I run the application through npm install -g serve & serve -s build. How to do it?
2 answers
You can access the environment variable NODE_ENV , and check its status:
const serverUrl = process.env.NODE_ENV === 'development' ? 'http://localhost:4000' : 'http://youdomain.com:4000' Or use the dotenv component, and create an .env file, write all the necessary environment variables into it, for example
REACT_APP_GOOGLE_CLIENT_ID = XXX-YYY-ZZZ.apps.googleusercontent.com REACT_APP_API_PROTOCOL = http: REACT_APP_API_HOST = localhost:3000 NODE_PATH = src/scripts PORT = 9001 And then run
"start": "react-scripts start dotenv_config_path=.env", "build": "react-scripts build dotenv_config_path=.env.production", And your variables will be properties of the process.env object process.env
I found the answer to my question. To organize this, you need to add two files to the project root:
.env
REACT_APP_BACKEND_DOMAIN=http://localhost:8080 .env.production
REACT_APP_BACKEND_DOMAIN=http://app.com and then in the code in the right place you get the variable process.env.REACT_APP_BACKEND_DOMAIN:
return fetch(process.env.REACT_APP_BACKEND_DOMAIN + '/topics', { method: 'GET' }).then((response) => response.json()); When running npm, the react will get the variable from the .env file. When producing, start serve -s build, react will get the variable already from the .env.production file.