How to implement OAuth in React

Implementing OAuth in React enables secure third-party authentication without handling sensitive user credentials directly in your application. As the creator of CoreUI with extensive React experience since 2014, I’ve integrated OAuth flows in numerous enterprise applications for simplified user onboarding. The most reliable approach redirects users to the OAuth provider, then handles the callback with authorization codes. This pattern provides secure authentication while offering users familiar login options from trusted platforms.

Implement OAuth by redirecting to the provider’s authorization URL and handling the callback with authorization codes.

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

function OAuthHandler() {
    const navigate = useNavigate()
    const location = useLocation()

    const initiateOAuth = () => {
        const clientId = process.env.REACT_APP_GOOGLE_CLIENT_ID
        const redirectUri = encodeURIComponent('http://localhost:3000/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`

        window.location.href = authUrl
    }

    return (
        <button onClick={initiateOAuth}>
            Login with Google
        </button>
    )
}

function AuthCallback() {
    const navigate = useNavigate()

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

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

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

This code initiates OAuth by constructing the authorization URL with your client ID and redirect URI, then redirects the user to Google’s authentication page. When the user returns via the callback route, it extracts the authorization code and exchanges it for access tokens on your backend. The tokens are then stored locally and the user is redirected to the application.

Best Practice Note:

This is the OAuth integration pattern we use in CoreUI dashboard applications for enterprise authentication. 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

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
What is globalThis in JavaScript?
What is globalThis in JavaScript?

How to Remove Elements from a JavaScript Array
How to Remove Elements from a JavaScript Array

How to Conditionally Add a Property to an Object in JavaScript
How to Conditionally Add a Property to an Object in JavaScript

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

Answers by CoreUI Core Team