How to hide API Keys in pure vanilla JavaScript?

Viewed 5148

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?

2 Answers

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.

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
Related