I have Phoenix app that, amongst other things, shows a map. I’ve set the map up using a Map service through a JS hook, and this service requires an access token to be passed.
I would like to read this access token from an environment variable, but can’t seem to find any documentation on a good way to do this (either through Elixir or directly accessing the env variable). Any suggestions?
There’s many ways to do this, but one way I like to do is to get the variable from within Elixir, at runtime or compile time - whatever works best, and then assign it as a “data-token” attribute to the document’s body in HTML. Then, from JavaScript you have to only fetch this attribute from document.body
As the env variable in question is a secret access token, I would like to avoid exposing it in the HTML. Have you tried any solutions that get around this issue?
Sorry if this wasn’t clear, but I need to access the env variable from JS, hence why I can’t use System.fetch_env. I’m looking for some way of either accessing the env variable directly from JS or pass it in a secure manner from Elixir.
There’s no “secure” passing of access tokens to JavaScript. Anything and everything that you expose to JavaScript, as an environmental variable fetched from JS or exposed by attribute or exposed some other way - anything that ends up in JavaScript runtime has already leaked.
well yes, that’s why I suggested exposing it as a body attribute, but there is a number of other ways to do it. You could have a HTTP endpoint that returns JSON of list of environment variables to be exposed at runtime. You could also use process.env.SOME_VARIABLE at compile time, when JS is being bundled, but that’s suboptimal too