skip to Main Content

So, I have a react app that uses process.env.API_BASE_URL in api utilities to connect to API.
Till now I have been using two webpacks: local and production to set the API_BASE_URL for dev and prod.

I want to change the API_BASE_URL after build. Stuck at this problem because the variables are embedded into the build as values and this build is supposed to be distributed to different clients so they can have separate backend url and changing webpacks is not an option as those are already very cluttered.
Below is my webpack code:

const GLOBALS = {
  'process.env': {
    NODE_ENV: JSON.stringify('production'),
    API_BASE_URL: JSON.stringify(
      config.API_BASE_URL || 'http://127.0.0.1'
    ),
    __BUILDVERSION__: JSON.stringify(commitHash),
    __BUILDTIME__: new Date().getTime(),
    __PRODUCTVERSION__: JSON.stringify(productVersion),
  },
};

The below code from main.js file:

  console.log(
    process.env.REACT_APP_API_BASE_URL,
    process.env.API_BASE_URL,
    process.env
  );

logs this output:

 undefined
 http://127.0.0.1
 { API_BASE_URL: "http://127.0.0.1", WS_BASE_URL: undefined, __BUILDVERSION__: commit, __PRODUCTVERSION__: "latest" }

I have a .env file in root folder, that contains

REACT_APP_API_BASE_URL="http://testurl"

I tried this solution but it didn’t work.

2

Answers


  1. You can not change basic env vars after build in react. If you want to change env vars on deployment, you can add REACT_APP_ as a prefix to your env vars that react will pick up.

    You can read more about using env vars in react here: https://create-react-app.dev/docs/adding-custom-environment-variables/

    Login or Signup to reply.
  2. As Simen pointed out, you cannot modify the ENV Vars after build. The result of the build is static.

    If you want to avoid re-building you can checkout https://dev.to/eslynn/how-to-dynamically-change-your-react-environment-variables-without-re-building-55el

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search