Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 559
JulienD Avatar asked Apr 28 '16 12:04

JulienD


People also ask

Where are environment variables stored in React?

Create React App supports custom environment variables without installing other packages. Using the . env file (This is the approach we are going to use). Through the shell (temporary, lasts as long as shell session last, and varies depending on the OS type).

Can JavaScript access environment variables?

To retrieve environment variables in Node. JS you can use process. env. VARIABLE_NAME, but don't forget that assigning a property on process.

How do I use Node js in frontend?

You can use Node's package manager npm instead of Bower for managing your frontend dependencies, for instance. And there's Browserify which will let you use npm packages that were designed for Node in your frontend JavaScript application (that runs inside the user's browser).


1 Answers

I ended up writing a conf.js file with content

window.CONFIG = {
    SOME_CONSTANT: 22,
}

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.

like image 133
JulienD Avatar answered Nov 11 '22 17:11

JulienD