I built a webapp that follows the javascript tutorials for google maps api, and now I’m looking to secure the api key by moving whatever functionality is needed to a node server and passing the values of interest up to the front end. My server function is sending the api all the same arguments and is getting back what looks like a valid script string, which I’m passing to the front end and running eval(result) on. The issue is when I run eval() the Google maps API responds that I’m missing the arguments I’ve previously sent.
Am I going about this all wrong? Should I rebuild purely for nodejs? Thank you for any help.
JS function on the node server:
async function startmaps(){
var payload = {
key: process.env.GOOGLE_MAPS_API_KEY,
libraries: ['places', 'geometry'],
callback: 'initMap'
};
var data = new FormData();
data.append("json", JSON.stringify(payload));
var result = fetch('https://maps.googleapis.com/maps/api/js',
{
method: "POST",
body: data
}
)
.then((res) => res.text())
.then((dat) => {
return {
data: dat,
error: false,
errMsg: ''
};
})
.catch((err) => {
return {
data: '',
error: true,
errMsg: err.toString()
};
});
return result;
}
Calling function on the front end:
async function StartMaps(){
var result = await fetch('http://localhost:3000/mapinit')
.then((res) => res.json())
.then((data) => {
return data;
})
.catch((error) => {
return error;
});
if(result.data === "undefined" || result.error){
console.log("got error");
}else{
eval(result.data);
}
}
End result:API errors on eval of result.data
Tried sending Google the sensitive data to initialize the maps from the backend, and passing up to the front end JS the result, however what Google maps API returns seems to realize it’s in another context and complains that it’s missing the api key
“VM403:208 Loading the Google Maps JavaScript API without a callback is not supported: https://developers.google.com/maps/documentation/javascript/url-params#required_parameters
….
util.js:63 Google Maps JavaScript API warning: NoApiKeys https://develope…”