1

I am new to javascripts. I am using Google Maps JavaScript API to include the Autocomplete functionality in my site. The code demands an API key to perform.

<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>

I want to protect this API key as this is publicly available and anyone canview my javascript code using view page source on the browser.

How can I protect this API key so that it can not be seen publicly??

Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72

2 Answers2

3

Since you are going to use this key from within Javascript in your frontend app, there is no foolproof way to secure it.

The best you can do is to restrict your api key with Application restrictions based on the Referer header, and API restriction to only the Maps API.

https://developers.google.com/maps/documentation/javascript/get-api-key#restrict_key

https://cloud.google.com/docs/authentication/api-keys#adding_http_restrictions

This makes it difficult for some other application to pose as your application as it is not trivial to imitate the Referer header, specially from a frontend app.

https://security.stackexchange.com/questions/152066/what-is-the-point-of-restricting-a-google-api-key-by-http-referer

gaurav5430
  • 12,934
  • 6
  • 54
  • 111
2

There are numerous sorts of API keys for Google Maps.

Browser / Javascript keys are meant to be used for fetching JS / Frontend libraries and are okay to use.

Simply ensure you're using a browser key, found here: https://developers.google.com/maps/documentation/javascript/get-api-key

You can further add security restrictions to prevent the key from being used elsewhere. You can restrict by domain, ip address, android, ios apps as well.

Note, server-side keys should be private.

Prateek Arora
  • 274
  • 2
  • 6