Skip to content

Instantly share code, notes, and snippets.

@sadeghbarati
Forked from srestraj/nuxt-3-gsi.md
Created November 2, 2022 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sadeghbarati/9ebaddf69dec41142a1f7fdad8643d5e to your computer and use it in GitHub Desktop.
Save sadeghbarati/9ebaddf69dec41142a1f7fdad8643d5e to your computer and use it in GitHub Desktop.
Integrate Google Sign-in with Nuxt 3.

Integrate Google Sign-in (Popup method) with Nuxt.js 3 - Works in Incognito mode as well

Add GSI client in your nuxt.config.ts
export default defineNuxtConfig({
  ...
  app: {
    head: {
      ...
      script: [
        {
          src: 'https://accounts.google.com/gsi/client',
        },
      ],
      ...
    }
  }
  ...
});
In your login page or component, add the Google Button div (this will be populated by the rendered button)
<div id="googleButton"></div>
Inside your mounted hook, initialize the Google Sign in and render the Sign in button
<template>
  <div id="googleButton"></div>
</template>
<script lang="ts" setup>

onMounted(() => {
   window.onload = () => {
    google.accounts.id.initialize({
      client_id: 'YOUR_CLIENT_ID',
      callback: handleCredentialResponse, //method to run after user clicks the Google sign in button
    });
    google.accounts.id.renderButton(
      document.getElementById("googleButton"),
      { theme: "outline", size: "large" } // customization attributes
    );
    google.accounts.id.prompt(); // also display the One Tap dialog
  }
})

function handleCredentialResponse(response) {
  // call your backend API here
  // the token can be accessed as: response.credential
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment