I am building an app using react & django rest framework.I can access all of data via axios url (127.0.0.1:8000). But when i deploy it to azure for production then the axios ip needs to change by azure container ip for requesting to the url. What is the best way to do this for production?
2 Answers
You can use environment variables by creating a .env file. You can have a .env.development file for development and a .env.production file for production.
When you are developing on your machine with npm start or yarn start, it will use the .env.development file in your application.
Note: You need to restart the development server after changing .env files for your changes to take effect during development.
When you build for production with npm build or yarn build, it will use the .env.production file.
.env.development
REACT_APP_AXIOS_URL="127.0.0.1:8000"
.env.production
REACT_APP_AXIOS_URL="http://yourapi.com"
Then your application code only needs to reference these variables through process.env.
axios.get(process.env.REACT_APP_AXIOS_URL)
Comments
You can use config for this purpose. It will create multiple configuration files which are loaded according to the application environment. In your scenario, you need to install config using:
npm i config
After that create a config folder in your project root. Create two files as default.json and production.json. Now you can create the JSON file like this with different value for both files/environments:
{
serverURL: "localhost:3000"
}
And then use variable like:
const config = require('config').default;
const url = config.get('serverURL');
Pass this url variable to axios while requesting. And it will automatically choose the IP depending on the environment set. When you create a react.js app build, it sets the environment to production. Hope this will help you.