-1

I am developing a product for my company. This product will not be SAAS and will be deployed at each client's server.

Provided that, I googled how to store api uris in React, but I just found about the using of enviroment variables provided by CRA (AKA .env file).

This does not fulfill my company requirements, that is just "build once, deploy anywhere", with a config key-value file (for instance something like 'APIURI': 'http://foo.bar') read at runtime instead of building the app each time I must deploy it, changing these enviroment variables.

I tried to read an external JSON file, but CRA blocks any import outside the src folder. I also tried this approach: https://stackoverflow.com/a/52184642/12570096 but in the end, it injectes the values too, so whenever I change the config file, it does not updates, so... I wonder if anyone knows any approach to achieve this scenario.

Thanks all!

3 Answers3

1

You should fetch the config instead of importing it. In your app instead of

import config from '../config.js';

Use

const config = fetch('/config.json')
// .then(...)

You ship your app with default config.json (next to your bundle.js). Then every company can edit it on its own.

Petr K.
  • 530
  • 6
  • 12
1

For those interested in this topic, using Redux you can fetch the config.json (as Petr suggested) at the beggining of the app.

After that, the first code lines from any action creator, have to get the current state (where we previously loaded the config) and there we can obtain the config:

export const fetchUsers = () => (dispatch, getState) => {
    const config = getState().config.config;
    const getUsers = `${config.API.BASE}/${config.API.USERS}`;
}

so getUsers contains the urls from the config store

0

Since you are using only client application

Problem

First of all, it must be clear that there is no such thing as environment variables inside the browser environment. Whichever solution we use nowadays is nothing but a fake abstraction.

But, then you might ask, what about .env files and REACT_APP prefixed environment variables which come straight from documentation? Even inside the source code, these are used as process.env just like we use environment variables inside Node.js.

In reality, the object process does not exist inside the browser environment, it’s Node-specific. CRA by default doesn’t do server-side rendering. It can’t inject environment variables during content serving (like Next.js does). During transpiling, Webpack process replaces all occurrences of process.env with a string value that was given. This means it can only be configured during build time.

So there are some work arounds, even i was also searched for a answer on this here

Since there was no exact solution i have found a reference workaround

Learner
  • 8,379
  • 7
  • 44
  • 82