Andyally
Andyally

Reputation: 1069

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?

Upvotes: 3

Views: 11020

Answers (2)

bhaRATh
bhaRATh

Reputation: 797

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;

Upvotes: 0

Murilo Cruz
Murilo Cruz

Reputation: 2551

So, you need to clearly understand what happens with your env variables and the build process.

When you build your create-react-app app, the process that builds it uses the .env file to transpile your code and bundle it. And It's output is STATIC HTML, js and CSS file.

This means that when you serve your already built app, the app code already have the .env inside the code, and there is nothing that process it when sending them to the browsers, and that's why you need to rebuild it every time you want to change the env variable

This shouldn't be a problem if you use create-react-app's .env file structure , and use a .env.development file for development with your base url in development (when you run yarn start) and a .env.production file with the base url for the production build. Everytime you want to change the value on the server, just update it and rebuild. If you want this to not be versioned on git, use .env.production.local instead

Upvotes: 12

Related Questions