2

I am implementing the Google Maps API in one of my projects and I need help hiding my API keys before I deploy my app on Netlify. Currently I am using the API keys in a script tag posted down below.

<script async defer
        src=`https://maps.googleapis.com/maps/api/js?key=${MY_API_KEY}&callback=initMap`
</script>

I am using pure vanilla JavaScript, and there are no frameworks or libraries being used. I have 3 files index.html, style.css and index.js. How should I go about achieving this?

doğukan
  • 23,073
  • 13
  • 57
  • 69
Harman
  • 158
  • 1
  • 9
  • 3
    Does this answer your question? [What steps should I take to protect my Google Maps API Key?](https://stackoverflow.com/questions/1364858/what-steps-should-i-take-to-protect-my-google-maps-api-key), [Do I need to hide API key when using google maps js API? If so, how?](https://stackoverflow.com/questions/38153734/do-i-need-to-hide-api-key-when-using-google-maps-js-api-if-so-how), [Protecting Google Maps JavaScript API key](https://stackoverflow.com/questions/43774920/protecting-google-maps-javascript-api-key). – Lawrence Cherone Jul 11 '20 at 21:21
  • It looks like I don't need to anything and it's ok to expose the browser API keys. Should I need to do anything on my google cloud platform account regarding this API? @LawrenceCherone – Harman Jul 11 '20 at 21:35
  • Im pretty sure without looking you can lockdown usage by domain, so only requests from your domain/origin will work for that key – Lawrence Cherone Jul 11 '20 at 21:38
  • Thanks! Appreciate the help – Harman Jul 11 '20 at 21:40
  • np yeah see https://cloud.google.com/docs/authentication/api-keys?hl=en-GB#api_key_restrictions for the *credential*, add website restrictions which you can your domain and also restricted to just that single api (maps js) – Lawrence Cherone Jul 11 '20 at 21:44

2 Answers2

1

You can't, if it's client side JavaScript.

You can proxy the call to a server you control, and input the API key there, that way the user in the browser can't see it.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
1

For any functionality in your application that requires you to communicate with a third party API you don’t control,

the answer is to make a simple CSRF secured AJAX call to your own back-end and then let your server-side application make the API call on behalf of your front-end then return the response back to your client-side app.

Update:

  • you can also whitelist domains
albseb
  • 169
  • 5