I'm trying to implement Place Autocomplete in my project. Google provides the following snippet to load the library<p><script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap">
</script><p>I know that I can .gitignore .env files and pass the API KEY as an env variable. I can also restrict the API KEY to accept requests from my referrer domain. I think even if I place my API KEY in .env files users can inspect element and see the key. I was wondering if it is possible to spoof a referrer and use my API KEY. I am currently making an api call to my backend server which relays the result to the front end but that adds unnecessary latency. Hence, if possible I would like to use the Google snippet. What are industry standard practices of loading the API KEY securely in Javascript?
Google has tools to restrict usage of your API key to certain HTTP referrers and apps.<p><a href="https://cloud.google.com/docs/authentication/api-keys?hl=en&visit_id=638343634249811087-3665802784&rd=1#api_key_restrictions" rel="nofollow noreferrer">https://cloud.google.com/docs/authentication/api-keys?hl=en&...</a><p>It's not perfect; there are ways to subvert it. But it makes it trickier for somebody to make much of a profit off it, reducing interest in stealing the key.
In essence, the best you can do is have an authorization dance that results in a short lived authentication token.<p>Or you could use some obfuscation like symmetrically encrypting the key, but clients will see the encryption key too (and in the inspector when Maps API is hit).<p>Or you could have a server side proxy, but that proxy will be publicly available too.<p>As frontend code works on the client, there is no real way to hide the API key, so I wouldn't really bother adding any complexity.