Integrate Google Sign-in (Popup method) with Nuxt.js 3 - Works in Incognito mode as well
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>
<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>
I think the code can also be written inside
onMounted
without the window object. Something I've implemented myself in one of my codes.