How to use Google login in React
Google Sign-In provides a streamlined authentication experience in React applications using Google’s official Identity Services library.
As the creator of CoreUI with extensive React development experience since 2014, I’ve integrated Google login in numerous production applications for enhanced user experience.
The most efficient approach uses the @google-cloud/local-auth or Google Identity Services for seamless authentication integration.
This method provides secure, user-friendly authentication while maintaining Google’s security standards and user trust.
Use Google Identity Services library to implement secure Google Sign-In with minimal setup.
import { useEffect, useState } from 'react'
function GoogleLogin() {
const [user, setUser] = useState(null)
useEffect(() => {
// Load Google Identity Services
const script = document.createElement('script')
script.src = 'https://accounts.google.com/gsi/client'
script.async = true
script.defer = true
document.body.appendChild(script)
script.onload = () => {
window.google.accounts.id.initialize({
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
callback: handleCredentialResponse
})
window.google.accounts.id.renderButton(
document.getElementById('google-signin-button'),
{
theme: 'outline',
size: 'large',
text: 'sign_in_with',
width: 250
}
)
}
return () => {
document.body.removeChild(script)
}
}, [])
const handleCredentialResponse = async (response) => {
try {
// Send JWT token to your backend for verification
const result = await fetch('/api/auth/google', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: response.credential })
})
const userData = await result.json()
setUser(userData)
localStorage.setItem('token', userData.token)
} catch (error) {
console.error('Google login error:', error)
}
}
const handleSignOut = () => {
setUser(null)
localStorage.removeItem('token')
window.google.accounts.id.disableAutoSelect()
}
return (
<div>
{user ? (
<div>
<p>Welcome, {user.name}</p>
<button onClick={handleSignOut}>Sign Out</button>
</div>
) : (
<div id="google-signin-button"></div>
)}
</div>
)
}
This code loads the Google Identity Services library and initializes the Sign-In button with your client ID. When users sign in, Google returns a JWT credential that you should verify on your backend. The component handles both sign-in and sign-out flows while maintaining user state and token management.
Best Practice Note:
This is the Google authentication setup we recommend in CoreUI applications for enterprise-grade user management. Always verify the JWT token on your backend server and never trust client-side validation alone for security-critical operations.



