DEV Community

loading...
Cover image for How to Integrate Google Login API Into Your React App
Quod AI

How to Integrate Google Login API Into Your React App

quod_ai_blog profile image Quod AI Originally published at quod.ai Updated on ・10 min read

We always want to make sign-ups to be frictionless and hassle-free. More people will be willing to try our app if onboarding is as easy as humanly possible. Nothing discourages sign-ups more than a form with a gazillion questions and pages of options.

This article was original posted at https://www.quod.ai/post/how-to-integrate-google-api-into-your-react-app

It is always advisable to use an authentication mechanism that people are already utilizing at this very moment. You can bet your lunch money that people are logged in to Facebook, Twitter, and Google at this instance while reading this article.

You can never go wrong providing a dead-simple mechanism for people already logged in to Google, Gmail, or YouTube, and just drop them at the center of your app, all logged in and ready to go.

Objectives

In this tutorial, we shall do the following:

  • Create a React application where a user can sign-in using his Google credentials;
  • Retrieve and display the user’s name, email, and profile image;
  • Allow the user to sign out of the app via a click of a button.

Prepare your Google API Project

To integrate Google Login into our React app, we need a Google Client ID. We can obtain this when we create a Google API Project.

  1. Go to the Google API’s Credentials Page

Image for post

  1. Hit the Create a project link, and choose a name to your fancy.

Image for post

  1. Once you have a project in place, proceed to Credentials > Create credentials > OAuth client ID.

Image for post

  1. To proceed any further, we need to create an OAuth consent screen first. Click on that button.

Image for post

  1. We choose External User Type since we want to give access to everyone with a Google account. The appropriate selection depends entirely on the app requirements.

Image for post

  1. Fill up the app registration form. For the most part, you can leave it blank.

Image for post

  1. Choose the scope best suited for the app that you shall develop. Since we are just making a demo application, I chose all available scopes.

Image for post

  1. Provide your email address as a test user. Note that this only matters when the project is in testing. Once we placed the status into production, the test users list will be irrelevant.

Image for post

  1. You shall see a summary of the OAuth content screen settings at the end of the registration flow.

Image for post

  1. After creating the OAuth consent screen, we head back to Credentials > Create credentials > OAuth client ID. Choose the Web application type. Choose an appropriate name for your client. Take note that we can provide the Authorized JavaScript origins and Authorized redirect URL’s on this page. We will come back to this page later. Hit the blue “Create” button to proceed.

Image for post

  1. We will see our Google Client ID.

Image for post

Have your React App ready

Once you have your Google Client ID with you, it’s time to integrate Google Login into your React application.

We start with a standard create-react-app application for demonstration purposes, but this will work as well with any existing React app that you already have.

$ npx create-react-app tutorial-react-google-api-login

We need to modify a couple of files to perform the integration.

Create a file named src/lib/GoogleLogin.js, with the following content:

View GoogleLogin.js in context with Quod AI

This file contains a single function named loadGoogleScript, which, as the name implies, loads the necessary JavaScript library needed to use Google API.
Upon closer inspection, we can see that this is a standard way of loading any JavaScript library. We can repurpose this function to load any JavaScript library just by replacing the src variable.

Line 7 (Ref. 1): This is the complete URL of the necessary JavaScript library that we need to fetch and load before using any of the Google API’s that we need.

Line 10 (Ref. 2): We access the first of all <script> tags available in our code. We are confident that we have at least one <script> tag in our document since React is a JavaScript library.

Line 13 (Ref. 3): This ensures that the script is loaded only once by checking the provided id first.

Line 14–18 (Ref. 4): We dynamically build our JavaScript tag and insert it before all existing tags.Line 17 (Ref. 5): We tell our code to run a globally available function named onGoogleScriptLoad after the Google API library loads properly. onGoogleScriptLoad is an arbitrarily-named function, and as such, can be named anything that you prefer. We shall use this function as an entry point for our React component, as we shall see later.

Proceed to our main application (src/App.js), and perform the following modifications:

View App.js in context with Quod AI

Lines 52–66 (Ref. 1): We define the onGoogleScriptLoad global function, which, as mentioned previously, will be the function to be executed immediately after the Google API Library has fully loaded.

Lines 54–55 (Ref. 2): We expose the gapi object as the gapi state to make it available to our whole React application. The gapi object acts like the root object that we use to load all other functionalities such as authentication (via gapi.auth2) and sign-in helper functions (via gapi.signin2)

Lines 57–65 (Ref. 3): We need to load gapi.auth2 like so as the library does not do this on the onset. The gapi.auth2.* family of functions is available for us once the library loads successfully.

Lines 59–61 (Ref. 4): We need to initialize gapi.auth2 before we can proceed any further. Remember the Google Client ID that we obtained while creating the Google API Project? We utilize it here.
Security warning: Do NOT commit your Google Client ID, or any sensitive information, in your source repository!
The current best practice is to put the client ID in your environment variable (in this case, as REACT_APP_GOOGLE_CLIENT_ID) to prevent placing the ID in the repository.

Line 62 (Ref. 5): Successful initialization of gapi.auth2 gives us a GoogleAuth object. This object allows us to sign in, sign out, and perform several other user-specific functions. There is much to explore with the GoogleAuth object, but for now, we shall use it for the GoogleAuth.signOut()function, as we shall see later on.
We expose this GoogleAuth object to the whole app as the googleAuth state.

Line 63, Lines 36–45 (Ref. 6): The Google library provides a nifty helper function called gapi.signin2.render to help us create our sign-in button. Provide the ID of the element where you want the button placed, and the library will automatically create the sign-in button for us.

Lines 16–22, Lines 24–26 (Ref. 7): The gapi.signin2.render function allows us to declare both a success and a failure callback. The success callback includes the handy googleUser object, which serves the entire activity’s ultimate objective: to retrieve valuable user data, including the user’s name, profile picture, and email address, and place them in their respective states for rendering.

Lines 28–34 (Ref. 8): When the user hits “Log Out,” we do two things. First, we invoke the GoogleAuth.signOut() function, and second, we re-render the Google sign-in button via gapi.signin2.render().
The sign-in button re-render is necessary since we removed the button from the DOM after login when it disappeared from view.

Line 69 (Ref. 9): Observe that we invoke the actual loadGoogleScript() function only after we defined window.onGoogleScriptLoad completely. We do this to be 100% certain that window.onGoogleScriptLoad is available before the library completes its load, and no race conditions happen.

Run the app, get the URL

Run the following command, replacing XXXXXXXXXX with your Google Client ID:

$ REACT_APP_GOOGLE_CLIENT_ID=XXXXXXXXXX npm start_

Our React application is now visible from our local machine, via http://localhost:8080. Such is not enough, though; we must expose our app to the world. We can do this securely by using ngrok.

$ ngrok http 8080

Image for post

Ngrok provides us with two URL’s that can be accessed anywhere on the Internet: an http version and an https version. Take the https version, in our case https://805b5b974a6d.ngrok.io. We shall go back to Google API to plug in the URL.

Reconfigure Google OAuth

Go back to Credentials > OAuth 2.0 Client IDs > (Your Client). Add the ngrok URL in both Authorized JavaScript origins and Authorized redirect URIs.

Image for post

Go back to the OAuth consent screen and ensure that we set its publishing status to production.

Image for post

View app, and enjoy

Now we go to the fun part, where we view and test our finished application.

Image for post

You can play around with the live demo here: https://compassionate-villani-96963b.netlify.app/

You can view and download our source code at: https://github.com/QuodAI/tutorial-react-google-api-login

I hope that you obtained something valuable today. Happy coding!

Discussion (0)

pic
Editor guide