How to use GitHub login in React

GitHub login provides seamless authentication for developer-focused React applications using GitHub’s OAuth2 flow for trusted user verification. As the creator of CoreUI with extensive React experience since 2014, I’ve integrated GitHub authentication in numerous developer tools and portfolio applications. The most reliable approach redirects users to GitHub’s authorization server and handles the callback with authorization codes. This method leverages GitHub’s robust authentication system while providing familiar login experience for developer users.

Implement GitHub OAuth by redirecting to GitHub’s authorization URL and handling the callback response.

import { useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'

function GitHubLogin() {
    const navigate = useNavigate()

    const handleGitHubLogin = () => {
        const clientId = process.env.REACT_APP_GITHUB_CLIENT_ID
        const redirectUri = encodeURIComponent('http://localhost:3000/auth/github/callback')
        const scope = encodeURIComponent('user:email')

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

        window.location.href = authUrl
    }

    return (
        <button onClick={handleGitHubLogin} className="github-login-btn">
            Login with GitHub
        </button>
    )
}

function GitHubCallback() {
    const navigate = useNavigate()

    useEffect(() => {
        const urlParams = new URLSearchParams(window.location.search)
        const code = urlParams.get('code')

        if (code) {
            fetch('/api/auth/github/callback', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ code })
            })
            .then(response => response.json())
            .then(data => {
                localStorage.setItem('token', data.token)
                localStorage.setItem('user', JSON.stringify(data.user))
                navigate('/dashboard')
            })
            .catch(error => console.error('GitHub auth error:', error))
        }
    }, [navigate])

    return <div>Processing GitHub login...</div>
}

This code initiates GitHub OAuth by constructing the authorization URL with your GitHub app’s client ID and redirect URI. When users return from GitHub, the callback component extracts the authorization code and exchanges it for an access token on your backend. The user data and token are then stored locally for subsequent API requests.

Best Practice Note:

This is the GitHub authentication pattern we use in CoreUI developer dashboard applications for seamless developer login. Always handle the token exchange on your backend to keep client secrets secure and implement proper error handling for failed authentication attempts.


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