How to integrate OAuth in Vue

Integrating OAuth in Vue applications enables secure third-party authentication without handling sensitive credentials directly in your application. As the creator of CoreUI with extensive Vue development experience since 2014, I’ve implemented OAuth flows in numerous production applications for simplified user onboarding. The most reliable approach uses Vue 3 Composition API with OAuth provider SDKs or manual redirect flows. This pattern provides secure authentication while offering users familiar login options from trusted platforms.

Implement OAuth authentication using Vue 3 Composition API with provider-specific redirect flows.

// composables/useOAuth.js
import { ref } from 'vue'
import { useRouter } from 'vue-router'

export function useOAuth() {
    const router = useRouter()
    const isLoading = ref(false)
    const error = ref(null)

    const loginWithGoogle = () => {
        isLoading.value = true
        const clientId = import.meta.env.VITE_GOOGLE_CLIENT_ID
        const redirectUri = encodeURIComponent(window.location.origin + '/auth/callback')
        const scope = encodeURIComponent('openid email profile')

        const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?` +
            `client_id=${clientId}&` +
            `redirect_uri=${redirectUri}&` +
            `scope=${scope}&` +
            `response_type=code&` +
            `state=google`

        window.location.href = authUrl
    }

    const loginWithGitHub = () => {
        isLoading.value = true
        const clientId = import.meta.env.VITE_GITHUB_CLIENT_ID
        const redirectUri = encodeURIComponent(window.location.origin + '/auth/callback')
        const scope = encodeURIComponent('user:email')

        const authUrl = `https://github.com/login/oauth/authorize?` +
            `client_id=${clientId}&` +
            `redirect_uri=${redirectUri}&` +
            `scope=${scope}&` +
            `state=github`

        window.location.href = authUrl
    }

    const handleCallback = async (code, state) => {
        try {
            isLoading.value = true
            const response = await fetch('/api/auth/oauth/callback', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ code, provider: state })
            })

            if (!response.ok) throw new Error('OAuth callback failed')

            const data = await response.json()
            localStorage.setItem('token', data.token)
            localStorage.setItem('user', JSON.stringify(data.user))

            router.push('/dashboard')
        } catch (err) {
            error.value = err.message
        } finally {
            isLoading.value = false
        }
    }

    return {
        isLoading,
        error,
        loginWithGoogle,
        loginWithGitHub,
        handleCallback
    }
}

// components/LoginForm.vue
<template>
  <div class="login-form">
    <button @click="loginWithGoogle" :disabled="isLoading">
      Login with Google
    </button>
    <button @click="loginWithGitHub" :disabled="isLoading">
      Login with GitHub
    </button>
    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>

<script setup>
import { useOAuth } from '@/composables/useOAuth'

const { isLoading, error, loginWithGoogle, loginWithGitHub } = useOAuth()
</script>

This code implements OAuth authentication for multiple providers using Vue 3 Composition API. The composable handles the OAuth flow by redirecting to provider authorization URLs and processing the callback with authorization codes. The backend exchanges codes for access tokens, ensuring client secrets remain secure.

Best Practice Note:

This is the OAuth integration pattern we use in CoreUI Vue enterprise applications for secure multi-provider authentication. Always implement proper error handling and consider using popup windows instead of redirects for better UX in single-page applications.


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 set focus on an input field after rendering in React
How to set focus on an input field after rendering in React

Passing props to child components in React function components
Passing props to child components in React function components

How to Manage Date and Time in Specific Timezones Using JavaScript
How to Manage Date and Time in Specific Timezones Using JavaScript

How to loop inside React JSX
How to loop inside React JSX

Answers by CoreUI Core Team