JulienD JulienD - 2 years ago 85
Node.js Question

Where to put frontend javascript configuration variables

I have a Javascript frontend that does Ajax calls to my backend. To do that, it needs a "backend_URL" that I hard-coded in the Ajax get() call, say "http://myservice/backend".

Now if I want to deploy my app on different machines, some of which will use this url with HTTPS: "https://myservice/backend", and some not (because they lack a proper certificate and do not expose valuable data).

Where should I put the "USE_HTTPS=1" config variable so that someone deploying the app can choose to use or not SSL ? Of course the question extends itself to other config variables.

I thought about adding a ".config" file at the project root, but then I don't know how to import it in my code. Or should I export environment variables ? Or a node.js feature ?

Answer Source

I ended up writing a conf.js file with content

window.CONFIG = {

and included it in a new <script> in my index.html before the other scripts. The window is not mandatory but shows where it comes from when I call that as window.CONFIG anywhere in the rest of the javascript.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download