7

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

3
  • 1
    You could simply ship a config.json file that holds all the environment-specific configuration values, the users can configure the application through that file as they please, leaving your bundled JS untouched and in tact. Commented Oct 16, 2018 at 8:58
  • only way you can get this to work then is to have a pre-flight XHR call that gets the env from a static file or server endpoint that your users will have to provide. Commented Oct 16, 2018 at 8:58
  • if I include a config.json, is there any way with react (app was created with create-react-app) to prevent it from being minified along with the rest of the app? This was my first thought but I don't really know about the actual build process and if the build would try to in-line anything like that when it's built. Commented Oct 16, 2018 at 9:05

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The easiest solution for me turned out to be to include a tag in my index.html what do you mean by tag in index.html here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.