Integrate Google Sign-in (Popup method) with Nuxt.js - Works in Incognito mode as well
Nuxt 3 version here.
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>
<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>
@Fanreza, if you set the
ux_mode
to redirect and then handle the response server-side, you can create your own custom button. More about this here: https://developers.google.com/identity/gsi/web/reference/js-reference#ux_mode. You can also have a look at this for other options: https://developers.google.com/identity/gsi/web/reference/html-reference. If you want to use it with the pop_up mode itself, I think you can try hiding the default Google button withvisibility: hidden
oropacity: 0
and then add your custom button. Something like we do for custom file inputs. I haven't tried it myself, but it might work I think.