mercredi 28 juillet 2021

How to configure dynamic environment variables for JS that will run in browser?

I have a requirement where system environment variables that we can get at server side (using process.env.BLABLA in Node.js) need also be injected in the pre-built JS file that will be served to the browser. The UI is made using Angular.

I have thought of three ways as of now in my mind :-

  1. an API call to /api/config to get these environment variables and using them.

  2. Let's say we have certain placeholder variable names in our JS files which will finally get bundled and served to browser. Before serving the bundled js file say , bundle.js, we replace those placeholders with the environment variables. The only thing is that bundle.js is quite huge (can't split it yet) and reading and writing might delay server start. Also don't know if this should be advocated.

  3. We can dynamically generate another file, say, config.js (at server startup) with the dynamic environment variables and a logic to store them in sessionStorage when loaded in browser. This file will be loaded via separate script tag in the index.html before bundle.js and then in bundle.js there would be logic to derive the environment variables using sessionStorage. The only thing here is that a person can see these variables using the dev tools. As of now, I don't think that's a concern. Also if the user resets sessionStorage to any other values, it shouldn't matter as the values would already be set and used at load time and cleared at the unload event.

What are some good ways to go about this ? The first one is quite simple but I want to prevent a request after bundle.js execution.




Aucun commentaire:

Enregistrer un commentaire