Skip to content

Instantly share code, notes, and snippets.

@sadeghbarati
Forked from srestraj/gsi-with-nuxt.md
Created November 2, 2022 11:30
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/4ee1d0d1b7a0c7dada09abd4b32b9ab5 to your computer and use it in GitHub Desktop.
Save sadeghbarati/4ee1d0d1b7a0c7dada09abd4b32b9ab5 to your computer and use it in GitHub Desktop.
Integrate Google Sign-in and One-tap with Nuxt.js

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

Nuxt 3 version here.
Add GSI client in your nuxt.config.js
export default {
  ...
  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>

export default {
  mounted() {
    // initialize Google Sign in  
    google.accounts.id.initialize({
        client_id: 'YOUR_CLIENT_ID',
        callback: this.handleCredentialResponse, //method to run after user clicks the Google sign in button
        context: 'signin'
      })
    
    // render button
    google.accounts.id.renderButton(
      document.getElementById('googleButton'),
      { 
        type: 'standard',
        size: 'large',
        text: 'signin_with',
        shape: 'rectangular',
        logo_alignment: 'center',
        width: 250
      }
    )
  },
  
  methods: {
    handleCredentialResponse(response) {
    
      // call your backend API here
      
      // the token can be accessed as: response.credential
    }
  }
}
</script>
If you also want the Google One-tap sign in, use the following inside the component or page you want to display one-tap.
<template>
...
</template>
<script>
  export default {
    mounted() {
      google.accounts.id.initialize({
        client_id: 'YOUR_CLIENT_ID',
        callback: this.handleCredentialResponse,
        context: 'signin',
      })
      google.accounts.id.prompt()
    },
    
    methods: {
      handleCredentialResponse(response) {
        // handle API calls same as above
      }
    }
  }
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment