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.



