Authenticate to Google Cloud text-to-speech API using native JavaScript

Viewed 119

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?

1 Answers

TL;DR

Is there any way for me to call the SynthesizeSpeech endpoint without utilizing OAuth?

Using Javascript, you must use OAuth. As shown in the Text-to-Speech documentation, the SynthesizeSpeech method requires the following OAuth scope: https://www.googleapis.com/auth/cloud-platform.


You should use the Google OAuth Library, instead of the old authentication method.

Here you can review the steps that show how your application interacts with Google's OAuth 2.0 server to obtain a user's consent to perform an API request on the user's behalf. Note that your application must have that consent before it can execute a Google API request that requires user authorization.

Related