3

Problem : I am new to React JS, and looking for an option to read environment configs from an external property file. This problem is more specific for one of my clients, who is looking to have an option to change the environment files dynamically. E.g. change the hostname/port dynamically whenever there is a change. The build process is not owned by my client. I create a minified final package, which my client deploys it on tomcat/web server.

Tried Solution : With some read-outs, I have configured .env files for different environments and able to successfully read configs from these files. However, these are more of a build process environment files. And, I am trying to find a way to read the configs from an external source after my package is created.

Possible solutions : Here is one possible approach I can think of -

Read external property file using libraries like "properties-reader". I will provide the property file as part of my release bundle (i.e. build folder). My client can change this property file whenever required.

Please suggest if this is the correct approach or is there a better solution to this problem?

Manu
  • 173
  • 2
  • 10

2 Answers2

7

A Solution which worked for me !!

1) Create a "config.js" file inside public folder of react project. Sample Content of the "config.js" file -

window.env = {
  API_DOMAIN_ADDR: "http://localhost:8080"
};

2) Refer "config.js" file inside index.html. Code for index.html will be -

<body>
    <div id="root"></div>
    <script src="%PUBLIC_URL%/config.js"></script>
  </body>

3) Now, content of the config.js file will be accessible to react code. Sample code to retrieve the value of config.js variables -

window.env.API_DOMAIN_ADDR

Add this code wherever variable value needs to be accessed. I added this in my service class which is making ajax call.

Manu
  • 173
  • 2
  • 10
0

I would suggest using something like Firebase Realtime DB. I had a similar requirement for pointing the App builds to production or development server APIs for my company. For this, we use to load a Firebase Config and from there the UI used to pick up the host server endpoint.

Advantages:

  • This saves you from deploying your build folder every time.
  • This is realtime and less prone to errors.
  • FirebaseDB is free for small stuff like this.

The second option is to create two environment files which I see you have already done.

Rishi Raj
  • 432
  • 4
  • 12
  • Thanks Rishi !! My client also has constraints with tech stack/software, as it takes time to get approval and endorsement. So, Firebase might not go well with my client. In addition, in order to call Firebase DB, I still need to have environment specific connection URLs, as db url will also be different from environment to environment. – Manu Nov 11 '19 at 06:15