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 ?
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).
To retrieve environment variables in Node. JS you can use process. env. VARIABLE_NAME, but don't forget that assigning a property on process.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With