I am working on a small project including react frontend and Java backend with two environments.
I struggle on the idea how to work with multiple environemnts, I declare API url using axios:
export default axios.create({
baseURL: `http://api.dev.project.local/api/v1`,
});
But this works only for one environment, how to change API url after the package is built? I don't think it is a good practise to create two builds (one for dev and one for prod), because it could create mess inside artifacts manager (we use Azure Artifacs Feed).
How do you solve this problem?
In case you are with create-react-app, and only need local and production environment go with Adding Custom Environment Variables build-in feature. Otherwise, a useful alternative is env-cmd. Note that default start and build create-react-app commands are using . env and .
The use cases for having multiple pages in a single React app are pretty simple. You can create a website, and easily classify different types of content on different pages. But, it should also be understood that the default implementation of React is made to use a single HTML file, and this is by design.
In case you are with create-react-app, and only need local and production environment go with Adding Custom Environment Variables build-in feature. Otherwise, a useful alternative is env-cmd.
Install env-cmd, as a development dependency:
npm i -D env-cmd
Add .env file (at project root, same for all environments):
REACT_APP_API_ENDPOINT = https://default.example.com
Add .env.qa file:
REACT_APP_API_ENDPOINT = https://qa.example.com
Add .env.staging file:
REACT_APP_API_ENDPOINT = https://stage.example.com
Add .env.production file:
REACT_APP_API_ENDPOINT = https://production.example.com
Update package.json
{
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"build:qa": "env-cmd -f .env.qa npm run-script build",
"build:staging": "env-cmd -f .env.staging npm run-script build",
}
}
Note that default start and build create-react-app commands are using .env and .env.production respectively, and have no need of env-cmd.
Ready to use in our code
const baseUrl = process.env.REACT_APP_API_BASE_URL;
And, we also can use env-cmd for start command at development environment.
i think you should use environment variables and create an .env file and its seprate from your project.
for more information you can react docs about environment variables
or you can use npm scripts variables
I hope it was useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With