'Secure google maps api key in an angular app
I'm using angular and google maps. In all the tutorials I find, the instruction says something as: add to your index.html code:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY" type="text/javascript"> </script>
In this method, the API key is stored in my source code - which is not recommended.
How do I do this differently in angular?
Solution 1:[1]
usually i will restrict my api key by referrer URLs.
https://developers.google.com/maps/api-key-best-practices#apply_apikey_restrictions
Solution 2:[2]
I know this was asked a while ago but I just came across this while looking for answers to the same question. Here's what I came up with:
- I protect my key by referrer URL.
- I created a service that holds my google maps types and modules imports. The service handles all things Google Maps API related. In the service, I created a string property of the google script tag with my api key in it, I also gave the script tag a custom
id=""
attribute. Then, in the constructor of my new service, I check for the existence of the tag withif ( !document.getElementById('my-custom-id') ) { append script }
if the tag is not found, the constructor will append it to the<head>
tag.
The intent is that the script tag is never present in the head tag unless the user is accessing a component that actually needs it. My implementation of this is behind a login, thus you need to be logged in to access the component with the Google Maps API functionality. Scrapers would need to bypass the login to find the script tag (not going to happen).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | HanJeaHwan |
Solution 2 | kenef |