Implementing Google Authentication using React and Node.js

Posted By :Mohd Ubaish |31st May 2023

Implementing Google Authentication using React and Node.js

 

In this tutorial, we will learn how to implement Google Authentication in a web application using React and Node.js. Google Authentication allows users to log in to your website using their Google credentials. This tutorial will guide you through the process in seven steps.

 

Step 1: Obtain Google Client ID

 

To implement Google Authentication, you need to obtain a Google Client ID. Follow these steps to generate your own Client ID:

  1. Go to the Google Developers Console.
  2. Create a new project or select an existing project.
  3. Navigate to the "Credentials" section and click on "Create Credentials."
  4. Select "OAuth client ID."
  5. Configure the OAuth consent screen with the necessary information.
  6. Choose the application type (web application in this case) and provide the necessary details.
  7. Once created, you will receive a Client ID. Make a note of this somewhere as we will need it later.

 

Step 2: Install Dependencies

 

In your React application, you need to install the "@react-oauth/google" library, which provides a way to implement social login, including Google Authentication. Run the following query to install the library:

 

Command : npm install @react-oauth/google

 

Step 3: Import the GoogleLogin Component

 

To use Google Authentication in your React application, import the GoogleLogin component from the "@react-oauth/google" package. Add the following line of code to the top of your React component file:

 

Code : import { GoogleLogin } from "@react-oauth/google";

 

Step 4: Add GoogleLogin Component to your Login Button

 

Next, use the GoogleLogin component as a parent for your Google login button. Pass the Google Client ID as a prop to the component. The GoogleLogin component has two callback functions: onResolve and onReject. The onResolve function is called when the login is successful, and you can make your login API call inside this function. The onReject function is called when something goes wrong with the authentication.



React Code : 

<GoogleLogin
  clientId={GOOGLE_CLIENT_ID}
  onResolve={(response) => {
    handleGoogleLogin(
      response.data.email,
      response.data.access_token,
      response.data.name,
      response.data.picture
    );
  }}
  onReject={(error) => {
    console.log(error);
  }}
>
  <img src={googleIcon} alt="" />
</GoogleLogin>
 

 

Step 5: Handle the Google Login Response

 

In the handleGoogleLogin function, you can handle the response received from Google after a successful login. Extract the necessary information from the response, such as the email, access token, name, and avatar image. You can then make a POST request to your backend API to verify the login and retrieve a JWT token.

 

React Code : 

 function handleGoogleLogin(email, token, name, avatarImg) {
  postRequest({
    url: "Your API URL",
    data: { email, token, name, avatarImg },
  })
    .then((response) => {
      console.log(response.data);
      if (response.data.success) {
        dispatch(userData(response.data.userData));
        dispatch(setLogin(true));
        toast.success(toCapitalCase(response.data.message));
        navigate(-1);
      } else {
        toast.error(toCapitalCase(response.data.message));
      }
    })
    .catch((e) => toast.error(e.message));
}
 

 

Step 6: Verify the Google Token in your Node.js Backend

 

In your Node.js server, create a function to verify the Google token. This function uses the Google API to validate the access token received from the frontend. If the token is valid, it returns true; otherwise, it returns false. Here's an example function.

 

async function verifyGoogleToken(token) {
  try {
    const response = await axios.get(
      `https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=${token}`
    );

    const { sub, email } = response.data;
    console.log("Token verified. User ID:", sub);
    console.log("User email:", email);

    return true;
  } catch (error) {
    console.error("Error verifying token:", error.message);
    return false;
  }
}
 

 

Step 7: Verify Token and Generate JWT in your Node.js Backend

 

After verifying the Google token in your Node.js backend, you can pass the user information received from the frontend (email, token, etc.) to your API's body. Call the verifyGoogleToken function and check if the token is valid. If the token is valid, you can generate a JWT token and send it back to the frontend.

 

const privateKey = process.env.privateKey;
const expiresIn = process.env.expiresIn;

const token = jwt.sign({ userId: foundUser._id, email }, privateKey, {
  expiresIn: expiresIn,
});

 

Conclusion

 

In this tutorial, we learned how to implement Google Authentication using React and Node.js. We covered the steps required to set up the frontend and backend for Google Authentication. By following these steps, you can add social login functionality to your website, allowing users to log in using their Google accounts.

I hope you found this tutorial helpful and that it helps you resolve any login issues you may have encountered. Happy coding!


About Author

Mohd Ubaish

Mohd Ubaish is a highly skilled Backend Developer with expertise in a wide range of technologies, including React, Node.js, Express.js, MongoDB, and JavaScript.With a deep understanding of both front-end and back-end development, he is currently dedicated to the development of TripCongo Web Discovery.He is committed to creating a user-friendly experience on the frontend while ensuring the seamless functionality of the backend. By staying up-to-date with the latest industry trends and advancements, he strives to provide innovative solutions and optimize the performance of the application.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us