I am trying to migrate my application from NodeJS to browser. However, I can't seem to find up-to-date examples of how to authenticate to the Google Cloud Platform in native JavaScript. In NodeJS I was using a service account key to authenticate, but as I understand it, you cannot use a service account key in the browser. My current code:
function AuthenticateToGoogleCloud() {
handleClientLoad();
/**
* Set required API keys and check authentication status.
*/
function handleClientLoad() {
gapi.client.setApiKey(CREDS["credentials"][0]["gcloud"]["GC_API_KEY"]);
window.setTimeout(checkAuth, 1);
}
/**
* Authorize Google API.
*/
function checkAuth() {
gapi.auth.authorize(
{
client_id: CREDS["credentials"][0]["gcloud"]["GC_CLIENT_ID"],
scope: CREDS["credentials"][0]["gcloud"]["GC_SCOPES"],
immediate: true,
},
handleAuthResult
);
}
/**
* Handle authorization.
*/
function handleAuthResult(authResult) {
console.log(authResult);
initializeApi();
}
/**
* Load the Google Cloud API.
*/
function initializeApi() {
gapi.client.load("texttospeech", "v1");
}
}
When I run this snippet I get the error
Uncaught TypeError: Cannot read properties of undefined (reading 'setApiKey')
Presumably because the example I got it from is outdated. How can I authenticate to the modern Google Cloud Platform using native JavaScript and with no prompt to a user?