Login with google: Implementing social login options in modern web applications has become a standard practice to enhance user experience and streamline authentication processes. One of the most popular options is Google OAuth login, which allows users to log in using their Google account. In this article, we will walk you through integrating Google OAuth login in a React application using the @react-oauth/google
package.
Prerequisites
Before we dive into the implementation, ensure you have the following:
- A React application set up.
- An OAuth 2.0 Client ID from the Google Developers Console.
If you haven’t already created a Client ID, you can follow the steps here to set one up.
Step 1: Install the Required Packages
First, you’ll need to install the necessary packages in your React project:
npm install @react-oauth/google axios
@react-oauth/google
provides a simple way to integrate Google OAuth into your React application.axios
is a popular HTTP client for making API requests.
Step 2: Create the Social Login Component
Next, we’ll create a SocialLogin
component that handles the Google login functionality. Here’s the complete code for the component:
import { useGoogleLogin } from '@react-oauth/google';
import axios from 'axios';
const SocialLogin: React.FC<any> = () => {
const login = useGoogleLogin({
onSuccess: async tokenResponse => {
const userInfo = await axios.get(
'https://www.googleapis.com/oauth2/v3/userinfo',
{ headers: { Authorization: `Bearer ${tokenResponse.access_token}` } }
);
// Sample userInfo structure
// const userInfo = {
// 'email' : "info@zrtechsolutions.com",
// 'email_verified' : true,
// 'given_name' : "John",
// 'name' : "John Doe",
// 'picture' : "https://lh3.googleusercontent.com a/234442352.....",
// 'sub' : "3242343242342432",
// }
console.log('google.data', userInfo?.data);
// Perform backend API call here
},
onError: error => console.error('Login Failed:', error),
});
return (
<div className="flex gap-5 mt-6 font-medium text-center whitespace-nowrap justify-between text-white">
<div
className="flex cursor-pointer min-w-[47%] gap-2 px-3 py-4 rounded-xl shadow-sm bg-neutral-800 items-center justify-center text-white"
onClick={() => login()}
>
<div className="my-auto">Login with Google</div>
</div>
</div>
);
};
export default SocialLogin;
Breakdown of the Code:
useGoogleLogin
Hook: This hook is provided by@react-oauth/google
and is used to initiate the Google login process.onSuccess
Callback: This function is triggered when the login is successful. It usesaxios
to fetch the user’s information from the Google API.- User Information: The fetched user information, such as email, name, and profile picture, is logged to the console. You can extend this by sending the data to your backend for further processing.
Step 3: Wrap the Application with GoogleOAuthProvider
To enable Google OAuth in your application, you need to wrap your main component (usually App.js
or Layout.js
) with the GoogleOAuthProvider
. Here’s how to do it:
import { GoogleOAuthProvider } from '@react-oauth/google';
export default function Layout({ children }) {
return (
<GoogleOAuthProvider clientId="<clientIDfromGoogleauth2.0>">
<div>{children}</div>
</GoogleOAuthProvider>
);
}
Replace <clientIDfromGoogleauth2.0>
with your actual Google OAuth 2.0 Client ID.
Step 4: Implement and Test the Login
Now that everything is set up, you can use the SocialLogin
component in your application wherever you want to provide the Google login option.
import SocialLogin from './SocialLogin';
function App() {
return (
<Layout>
<SocialLogin />
{/* Other components */}
</Layout>
);
}
Conclusion
Integrating Google OAuth login into your React application is a great way to provide users with a seamless and secure authentication process. By following the steps outlined in this guide, you can easily set up Google login functionality using @react-oauth/google
and axios
. Remember to replace placeholders with your actual data and customize the component according to your application’s design and requirements.