Skip to content
codeaihub.in
Menu
Menu

How to Integrate Google Login in React and Fetch User Information

Posted on January 11, 2025January 27, 2025 by Tech Writer

Google Login in React

In modern web applications, user authentication is a critical feature. One of the most convenient methods is using Google Login, which allows users to sign in quickly with their Google account. In this guide, we’ll walk through how to integrate Google Login into your React app using the useGoogleLogin hook and how to fetch additional user information, such as their name and email.

Why Use Google Login?

Google Login provides several benefits for your users:

  1. Convenience: Users don’t have to create a new account or remember another password.
  2. Security: Google provides robust security mechanisms, reducing the chances of unauthorized access.
  3. User Experience: It’s a familiar and fast way for users to log in, which can improve conversion rates.

Step-by-Step Guide to Google Login Integration in React

1. Install the Required Packages

To start, you’ll need to install the @react-oauth/google package, which provides hooks for integrating Google Login in React.

npm install @react-oauth/google

2. Use the useGoogleLogin Hook

The useGoogleLogin hook simplifies the authentication process. Here’s how to implement it:

import React from "react";
import { useGoogleLogin } from "@react-oauth/google";

const GoogleLoginButton = () => {
  const login = useGoogleLogin({
    onSuccess: async (tokenResponse) => {
      console.log("Access Token:", tokenResponse.access_token);

      // Fetch user information after successful login
      try {
        const userInfo = await fetchUserInfo(tokenResponse.access_token);
        console.log("User Info:", userInfo);
      } catch (error) {
        console.error("Error fetching user info:", error);
      }
    },
    onError: (error) => {
      console.error("Login Failed:", error);
    },
  });

  return <button onClick={login}>Login with Google</button>;
};

export default GoogleLoginButton;

Explanation of the Code

  • useGoogleLogin Hook: This hook is used to initiate the login flow. It returns a function (login) that triggers the Google sign-in process when called (e.g., when the user clicks the button).
  • onSuccess Callback: This function is triggered when the login is successful. The tokenResponse contains the access_token, which is required for making authenticated requests.
  • onError Callback: If there’s an issue with the login process, this callback is triggered to handle the error.

3. Fetch User Information

Once the user is authenticated, you can use the access_token to fetch additional user details from Google’s UserInfo API. Here’s how to make the API request using axios:

import axios from "axios";

const fetchUserInfo = async (accessToken) => {
  const response = await axios.get("https://www.googleapis.com/oauth2/v3/userinfo", {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });

  return response.data;
};

Explanation of Fetching User Info

  • API Request: We’re sending a GET request to Google’s UserInfo API, including the access_token in the Authorization header.
  • Response: The response contains user details like the user’s name, email, and profile picture.

Example UserInfo API Response

When the API returns the user details, you might get a response like this:

{
  "sub": "1234567890",
  "name": "John Doe",
  "given_name": "John",
  "family_name": "Doe",
  "picture": "https://lh3.googleusercontent.com/a-/AOh14...",
  "email": "johndoe@gmail.com",
  "email_verified": true,
  "locale": "en"
}

Here’s what the response contains:

  • sub: The unique Google user ID.
  • name: The full name of the user.
  • given_name: The user’s first name.
  • family_name: The user’s last name.
  • picture: The URL to the user’s profile picture.
  • email: The user’s email address.
  • email_verified: Whether the user’s email is verified.
  • locale: The user’s language preference.

Why Fetch Additional User Information?

Fetching additional user information is helpful in many scenarios, including:

  • User Personalization: You can personalize the app experience with the user’s name, profile picture, or preferences.
  • User Database: You can save the user’s information in your database for future interactions.
  • Analytics: Collect user data (with consent) to analyze app usage and improve user experience.

Handling Google Login Errors

It’s essential to handle errors gracefully to provide a smooth user experience. Common errors include:

  • Popup Closed by User: If the user closes the login popup without completing the authentication process.
  • Invalid Token: If the access token is invalid or expired.

Make sure to provide meaningful error messages to the user so they know what went wrong. Here’s how you can handle errors:

onError: (error) => {
  console.error("Login Failed:", error);
  alert("There was an error with your Google login. Please try again.");
}

Security Considerations

While handling authentication, consider the following security best practices:

  1. Backend Token Validation: Always validate the access_token on the backend. Never rely solely on frontend authentication.
  2. Use HTTPS: Ensure your app uses HTTPS to securely transmit sensitive data.
  3. Token Expiration: Access tokens expire after a certain period. Ensure your app can handle token renewal.

Conclusion

Integrating Google Login into your React app is a straightforward process that enhances user experience by allowing them to authenticate easily. By fetching additional user information, you can personalize the app and provide more engaging features. Follow the steps outlined in this guide to implement Google Login and start building secure and user-friendly applications.

Category: javascript, React

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Agent2Agent (A2A): A New Way for AI Helpers to Work Together
  • 🤖What is a Kubernetes Cluster? A Beginner-Friendly Guide for GKE Users
  • CASA Ratio: Meaning, Formula, Importance & Impact on Banks
  • Liquidity Coverage Ratio (LCR): Importance, Formula & Impact on Banks
  • Deposit Growth in Banking: Trends, Formula, Impact & Key Drivers

Recent Comments

No comments to show.
© 2025 codeaihub.in | Powered by Minimalist Blog WordPress Theme