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.
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.
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.
- Go to the Google API’s Credentials Page
- Hit the Create a project link, and choose a name to your fancy.
- Once you have a project in place, proceed to Credentials > Create credentials > OAuth client ID.
- To proceed any further, we need to create an OAuth consent screen first. Click on that button.
- 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.
- Fill up the app registration form. For the most part, you can leave it blank.
- 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.
- 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.
- You shall see a summary of the OAuth content screen settings at the end of the registration flow.
- We will see our Google Client ID.
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:
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
Line 13 (Ref. 3): This ensures that the script is loaded only once by checking the provided id first.
Proceed to our main application (src/App.js), and perform the following modifications:
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 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
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.
Go back to the OAuth consent screen and ensure that we set its publishing status to production.
Now we go to the fun part, where we view and test our finished application.
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!