'Changing Axios baseUrl accessible from env file after building React App
Currently I am using .env file placed in react app root folder with variable
REACT_APP_BASE_URL = http://localhost:8081
I user axios defaults to set base url for api requests
Axios.defaults.baseUrl = process.env.REACT_APP_BASEURL
After building React App .env file is not considered and in case I have my base URL changed, how can I do that without re-building whole React App. I want to make base url independent, so I can dynamically change base url. What would be the best solution for that?
Solution 1:[1]
BaseUrl:
const defaultSettings = {
DEV_REACT_APP_BASE_URL: 'http://localhost:3001',
REACT_APP_BASE_URL: 'https://example.com',
};
const settings = {defaultSettings, ...process.env};
export default settings;
AXIOS baseUrl:
import axios from "axios";
import settings from "./settings";
const instance = axios.create({
baseURL:
process.env.NODE_ENV == "production"
? settings.defaultSettings.REACT_APP_BASE_URL
: settings.defaultSettings.DEV_REACT_APP_BASE_URL,
timeout: 1000,
headers: { "Content-Type": "application/json" },
});
export default instance;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bhaRATh |
