How to store environment-specific configuration used in Javascript code?

Hi everyone,

In the Phoenix application, I have a React code in the assets/javascript/ folder. I’m using Brunch and Babel (added by the framework).

At some point I needed to add a configuration variable containing the client_id for Google API. The config is needed in React part of the app and it should be different depending on the environment (dev & test, prod). Ideally, it should be stored outside of the Git repository.

The questions is how should I store and access the config. My idea was to use environment variables and access them using process.env in Javascript.

The problem is that it doesn’t work:

After running GOOGLE_CLIENT_ID=123 mix phoenix.server, the value of process.env.GOOGLE_CLIENT_ID in Javascript code is undefined. I’m not sure why. It worked for me in Rails 5.2 with Webpack and React.

What solution would you recommend for the Phoenix and React app?

Best,
Marek

Where is your JavaScript code running? On the server or in the browser?

Setting an environment variable at the point you run your server would do nothing to transfer that environment variable to the browser. From searching for process.env on the internet it looks like it’s part of Node.js. So it would be available to a server-side component running in JavaScript, but it doesn’t really look relevant to client-side JavaScript in the browser.

The roughly equivalent call for Elixir on the server side is System.get_env. That let you should see your client ID as you’ve set it on your mix line. Transferring that securely to the browser would probably involve using HTTPS or some other encryption in a server to client transfer step (say an API call).

With webpack that would be accomplished with something like

See also: Should I move from brunch to webpack?

I’m using Brunch and Babel (added by the framework).

I assume that “the framework” refers to Phoenix.

https://github.com/phoenixframework/phoenix/pull/2779

Description how to use webpack 4 (with Phoenix 1.3.x) instead of brunch:

alternate

That being said recommended practice is to limit the reliance on environment variables to one, single variable typically process.env.NODE_ENV - which is then used to select the correct module (e.g. settings.prod.js vs. settings.dev.js) to include in the generated JS bundle.

SurviveJS: Choosing which module to use


A similar approach seems to be possible with brunch with the jsenv-brunch plugin (npm).

Many thanks!

Could someone explain how would people use environment variables in their front-end (react) now that we’re using esbuild in Phoenix please?

1 Like