How to add GitHub login in Vue

Adding GitHub login in Vue provides users with familiar authentication while leveraging GitHub’s secure OAuth infrastructure for seamless developer-focused applications. As the creator of CoreUI with extensive Vue experience since 2014, I’ve integrated GitHub authentication in numerous developer tools and enterprise applications for streamlined user onboarding and access control. The most reliable approach involves creating a GitHub OAuth App and implementing the authorization flow using Vue composables for state management and API communication. This method ensures secure token handling while providing excellent user experience for developer-centric applications and tools.

Implement GitHub OAuth flow using Vue composables to handle authentication state and API integration.

import { ref, onMounted } from 'vue'

export function useGitHubAuth() {
    const user = ref(null)
    const isLoading = ref(false)
    const error = ref(null)

    const GITHUB_CLIENT_ID = process.env.VUE_APP_GITHUB_CLIENT_ID
    const REDIRECT_URI = `${window.location.origin}/auth/callback`

    const initiateGitHubLogin = () => {
        const scope = 'user:email'
        const authUrl = `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&scope=${scope}`
        window.location.href = authUrl
    }

    const exchangeCodeForToken = async (code) => {
        try {
            isLoading.value = true
            error.value = null

            const response = await fetch('/api/auth/github', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ code, redirect_uri: REDIRECT_URI })
            })

            if (!response.ok) {
                throw new Error('Authentication failed')
            }

            const data = await response.json()
            user.value = data.user
            localStorage.setItem('github_token', data.access_token)

        } catch (err) {
            error.value = err.message
        } finally {
            isLoading.value = false
        }
    }

    const fetchUserProfile = async (token) => {
        try {
            const response = await fetch('https://api.github.com/user', {
                headers: { Authorization: `Bearer ${token}` }
            })

            if (response.ok) {
                const userData = await response.json()
                user.value = userData
            }
        } catch (err) {
            console.error('Failed to fetch user profile:', err)
        }
    }

    const logout = () => {
        user.value = null
        localStorage.removeItem('github_token')
        error.value = null
    }

    onMounted(() => {
        const token = localStorage.getItem('github_token')
        if (token) {
            fetchUserProfile(token)
        }

        // Handle OAuth callback
        const urlParams = new URLSearchParams(window.location.search)
        const code = urlParams.get('code')
        if (code) {
            exchangeCodeForToken(code)
            // Clean up URL
            window.history.replaceState({}, document.title, window.location.pathname)
        }
    })

    return {
        user,
        isLoading,
        error,
        initiateGitHubLogin,
        logout
    }
}

This code creates a complete GitHub authentication system using Vue 3’s Composition API that handles the OAuth flow from initiation through token exchange and user profile retrieval. The composable manages authentication state, handles OAuth callbacks, and provides methods for login initiation and logout. It integrates with your backend API for secure token exchange while maintaining user session state through localStorage for persistence across browser sessions.

Best Practice Note:

This is the GitHub authentication pattern we use in CoreUI developer tools for secure, developer-friendly authentication workflows. Always validate GitHub tokens on your backend server and implement proper error handling for network failures and authentication errors.


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