Peko Chan
Peko Chan

Reputation: 364

Google Auth OAuth 2.0 SvelteKit wierd behavior

I am using Google Auth OAuth 2.0 One Tap Sign and Sveltekit, and I got some really weird behavior, I followed this doc https://developers.google.com/identity/gsi/web/guides/overview with javascript

onMount(async () => {
    const handleCredentialResponse = async (response) => {
        console.log('Encoded JWT ID token: ' + response.credential);
        };
    google.accounts.id.initialize({
        client_id: clientId,
        callback: handleCredentialResponse,
    });
    google.accounts.id.renderButton(
        document.getElementById('buttonDiv'),
        { theme: 'outline', size: 'large' } // customization attributes
    );
    google.accounts.id.prompt(); 
});
the code from the doc.
Sometimes it works everything goes well,
Sometimes I got

Hope someone can understand and help.
Do we have any way to check logs for investigation?

Upvotes: 3

Views: 1346

Answers (1)

Leftium
Leftium

Reputation: 17903

enter image description here

I got your code to successfully run without modification: https://google-signin-kit.vercel.app/ (This app is in "dev" mode so signin may only succeed with my Google account. If you clone my repo and set your Google client id, signin will work for you.)

I would check how my code is different from your code outside onMount(). For example, how did you include the Google javascript? I describe one major change below.

You also need to check your Google app settings. [GSI_LOGGER]: The given origin is not allowed... is fixed by adding the HTTPS app domain to your Google app "Authorized JavaScript origins." Non-HTTPS domains are not allowed. For example, these domains would not work:


ReferenceError: google is not defined (sometimes) happens because onMount() runs before the Google script is loaded.

  • To get a consistent reproduction, USB debug/inspect Android Chrome and set "disable caching" and throttling to "Slow 3G." (I could not reproduce on desktop Chrome).
  • Fixed by removing defer async when including Google's script: <script src="https://accounts.google.com/gsi/client"></script>
  • It should also be possible to call a function after the script is loaded, but I got inconsistent results in SvelteKit. For some reason Kit doesn't always call the load function. Possibly a bug?
  • Ideally, the Google script should be imported, but I couldn't find a version of the Google script that was built for importing. You may be able to construct a library that you can import? Importing would compile the Google script code into your app, tree-shaking the unused portions. Thus saving a network request and bandwidth.
  • Another workaround is to have your onMount function check for the google variable. If google is still undefined, call your function again after a certain timeout.

Upvotes: 2

Related Questions