Accessing environment variables in Javascript hook

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

1 Like

Thanks for the suggestion!

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?

So what’s the problem with using System.fetch_env?

This is not avoidable. If the javascript on the page can get it, so can a user. This is expected and normal.

1 Like

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.

I mean you can inject it in your JS code through Elixir’s templating but then that token can be read by anyone as @benwilson512 said.

You probably should put the responsibility of consuming the token and operating on the map on Elixir’s backend code, otherwise your token will leak.

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.

Is this Google Maps that you’re working with?

Ah, this didn’t click for me before, but totally makes sense. Thanks!

Yeah, I see how that makes sense now :sweat_smile: I’m working with Mapbox.

1 Like

ah I’m not sure about this one, never used it

This is in itself quite impossible as the JS is running in the browser while the env variable exists on the server.

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

I know, I just wanted to “say” it out loud.

1 Like