.env variables in dynamic script

So I've made a really simple weather app using google maps api and I would like to push it to git and then deploy it. I'm running into the issue of hiding my api key. I've tried using a dot.env variable, but I can't seem to get the script to run. Originally I used an "async defer src=" within a tag, but was unable to properly concatenate (is this the right term?)the src. One suggestion was to create the script dynamically, which I have done, but now can't get the map to render. I was also told to use a web pack to compile it (???). I am still pretty new to programming so I'm not sure how to make this work. I will provide some code below:

<script>

    function initMap() {
        let lat = <%= data.coord.lat%>;
        let lng =   <%= data.coord.lon%>;
        let center = {lat: lat, lng: lng };
        console.log(lat, lng);
        let map = new google.maps.Map(document.getElementById("map"), {
              zoom: 8,
              center: center,
              scrollwheel: false
          });
        let marker = new google.maps.Marker({
              position: center,
              map: map
          });
        marker.addListener('click', function() {
            infowindow.open(map, marker);
          });
        };

const script = document.createElement('script');
script.defer = true;
script.async = true;
script.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.GOOGLE_API_KEY}&callback=initMap`;
document.appendChild(script);
</script>

Here is my initial attempt. This renders the map, but cannot use the .env variable:

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

I've been trying for weeks to get this work so I can push and deploy. If anyone could help out I'd really appreciate it!!

1 answer

  • answered 2020-01-17 02:28 Hiren Patel

    You cannot really hide any script tag or client side javascript code that will be loaded on a browser. Even if you use webpack to compile it will be still visible to anyone who visits the site and knows how to use developer tools.

    You just need to restrict access for api key to your site so that no other site use your api key.

    Here are best practices on how to protect your api key from Google: https://developers.google.com/maps/api-key-best-practices