Secure API key in component

I have a simple map component that is using google-map-react:

import React from 'react';
import GoogleMapReact from 'google-map-react';

export const Map = ({location, zoomLevel}) => (
	<div className="map">
		<div className="google-map">
			<GoogleMapReact
				bootstrapURLKeys={{key: ""}}
				defaultCenter={location}
				defaultZoom={zoomLevel}
			>
			</GoogleMapReact>
		</div>
	</div>
);

Everything was working fine when I had the API hardcoded, but I am having trouble determing the best way to pass my API key to bootstrapURLKeys securely.

It’s not important how you pass it because the user can read the key anyway. But you can configure the key so it can be used only on your website domain.

This makes perfect sense, thanks.

Hi @naokotani,

if you just need a point on a map, you might consider the free map viewing in Google which is via an embed. JS SDK for maps is at cost though you have a free usage … in the past it used to be 25.000 views or so and I think today it goes agains a “free” 300 USD google gives you on new accounts (not sure if they still do that).
You can embed a map (and avoid loading another NPM) like this:

<iframe width={340} height={340} frameBorder='0' scrolling='no' marginHeight='0' marginWidth='0' allowFullScreen src={`https://www.google.com/maps/embed/v1/place?key=your_key&zoom=12&q=${lat},${lng}`} />

If you need more complex maps and functions, ### React Leaflet is very features full.

If you want to load the google maps object withtout importing and NPM, you can just add it to your header. The point is to avoid loading another NPM that counts in your bundle size.

Example:
Before you load a page that contains a map (useEffect in react) call a function to load your google maps library.

const loadGoogleMaps = () => {
  if (!window.google?.maps) {
    const script = document.createElement('script')
    script.src = 'https://maps.googleapis.com/maps/api/js?key=your_key&libraries=places' // and the library you need
    script.defer = true
    document.head.appendChild(script)
  }
}

export { loadGoogleMaps }

My plan is to create a map that can show the route for a sailing race and allow for users to click on different points to see pictures of the route. I will check out this leaflet maps.

Please get back if you reach a dead end with your implementation. I did this in the past, not with Google tools (I suppose they offer everything for that) but with Leaflet.