What I’m trying to do:
What I’m trying to do is to pass a secret to a JS function in Native libraries. In my specific case the secret is the Google Maps Key.
Here is my example code: Code Sample:
<script defer src="https://maps.googleapis.com/maps/api/js?key=[GOOGLE_KEY]&libraries=places">
</script>
<script>
function addAutocomplete(text_input_DOM) {
var autocomplete = new google.maps.places.Autocomplete(text_input_DOM);
}
</script>
that is called in the client by the following code:
def address_box_show(self, **event_args):
"""This method is called when the TextBox is shown on the screen"""
self.call_js('addAutocomplete', anvil.js.get_dom_node(self.address_box))
I looked at the documentation but I couldn’t find how to pass the GOOGLE_KEY secret to the JS code. Can someone please help me?
Do you mean a value stored in the Secrets service? Secrets cannot be used from client code, since that defeats the purpose of keeping them secret. Anything sent to the client can be seen by anyone sufficiently motivated.
The normal approach would be to make a server call and make the API call from there, where you can access the secret.
Or, create a restricted API key that is safe to expose in Javascript.
Exactly!
So, if I understood well, what you suggest is to call the Places API from the server side and in that case I can directly use python code and completely avoid JS. Am I right?
The problem in my case is that the Key is required when I import the external JS library, in this case:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places".
So how can I load the library (the code is in Native libraries) without exposing my key?
Sorry but is my first time using JS and I want to be sure and thanks for your time.
You cannot. Anything in Javascript is automatically exposed. Google allows you to place various restrictions on your API key for that reason. Narrow down what someone can do with the API key to limit abuse.
This is not specific to Anvil, if you do searching on Google Maps Javascript libraries and the API key, you’ll find a lot of people asking the exact same question.