How to add Google login in Vue

Adding Google login in Vue provides users with a convenient authentication method while leveraging Google’s secure OAuth infrastructure for user management. As the creator of CoreUI with extensive Vue experience since 2014, I’ve integrated Google authentication in numerous enterprise applications for streamlined user onboarding. The most reliable approach uses Google’s Sign-In API with Vue composables to handle the authentication flow and user data management. This method ensures secure token handling while providing a smooth user experience for both registration and login processes.

Use Google Sign-In API with Vue composables to implement secure Google OAuth authentication flow.

import { ref, onMounted } from 'vue'

export function useGoogleAuth() {
    const isLoaded = ref(false)
    const user = ref(null)

    const initializeGoogleAuth = () => {
        return new Promise((resolve) => {
            if (window.google) {
                resolve()
                return
            }

            const script = document.createElement('script')
            script.src = 'https://accounts.google.com/gsi/client'
            script.onload = resolve
            document.head.appendChild(script)
        })
    }

    const handleCredentialResponse = async (response) => {
        try {
            const credential = response.credential
            const decoded = JSON.parse(atob(credential.split('.')[1]))

            const authResponse = await fetch('/api/auth/google', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ token: credential })
            })

            const userData = await authResponse.json()
            user.value = userData.user
            localStorage.setItem('token', userData.token)

        } catch (error) {
            console.error('Google auth error:', error)
        }
    }

    const initializeButton = () => {
        window.google.accounts.id.initialize({
            client_id: process.env.VUE_APP_GOOGLE_CLIENT_ID,
            callback: handleCredentialResponse
        })

        window.google.accounts.id.renderButton(
            document.getElementById('google-signin-btn'),
            { theme: 'outline', size: 'large' }
        )
    }

    const signOut = () => {
        window.google.accounts.id.disableAutoSelect()
        user.value = null
        localStorage.removeItem('token')
    }

    onMounted(async () => {
        await initializeGoogleAuth()
        initializeButton()
        isLoaded.value = true
    })

    return { user, isLoaded, signOut }
}

This code creates a complete Google authentication system using Vue 3’s Composition API that dynamically loads the Google Sign-In library and handles the OAuth flow. The composable manages the authentication process, decodes JWT tokens, and communicates with your backend API for user verification. It provides methods for initialization, sign-out, and user state management while ensuring secure token handling throughout the authentication lifecycle.

Best Practice Note:

This is the Google authentication integration we use in CoreUI dashboard applications for enterprise-grade OAuth implementation. Always validate Google tokens on your backend server and implement proper error handling for network failures and authentication rejections.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Open All Links in New Tab Using JavaScript
How to Open All Links in New Tab Using JavaScript

How to Get Unique Values from a JavaScript Array
How to Get Unique Values from a JavaScript Array

What is Double Question Mark in JavaScript?
What is Double Question Mark in JavaScript?

How to force a React component to re-render
How to force a React component to re-render

Answers by CoreUI Core Team