Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic configuration variables in Javascript / React

I am writing a Client / Server application with the front end UI based in React. As a back-end Unix developer web technologies are not my forte so this is all new to me.

I need to be able to configure the UI to point to the server's URL and also to set other preferences. The typical react approach seems to be to use .env environment variables. However, as per this link: multiple-environments-with-react 'the “environment variables” will be baked in at build time'. This does not work for me as the application is an OEM offering to be sold to customers who would configure it themselves for their own environment. I do not know their server URLS at build time so I need a way that I can deliver the pre-built (minified / linted, etc) JS to them in a single archive and let them edit some sort of properties file to configure it for their needs.

What would the general JavaScript / React best practice be for this sort of use case?

Thanks,

Troy

like image 543
Troy Peterson Avatar asked Oct 16 '18 08:10

Troy Peterson


1 Answers

The easiest solution for me turned out to be to include a tag in my index.html. This gets minified during the NPM build but it does not get bundled with the other javascript so it can easily be replaced with another file at deploy time. My config.js looks like this:

config = {
    "title": "Application Title",
    "envName": "LocalDev",
    "URL": "localhost:8090"
}

Then inside my react components they're accessible by using:

const config = window.config;
alert("Application branding title is: " + config.title);

I will now have various config.js files for each environment (config.js.dev, config.js.uat, config.js.prod, etc) and at deployment I will link or renmae the appropriate one to config.js.

like image 118
Troy Peterson Avatar answered Sep 19 '22 14:09

Troy Peterson