Chimezie Innocent I am Chimezie, a software developer based in Nigeria. I am highly skilled in HTML, CSS, and JS to build web-accessible and progressive apps. I'm also skilled with React for web, React Native for Android apps, and Tailwind CSS. I write technical articles, too.

The guide to adding Google login to your React app

7 min read 2152

There are times when we just want to use an application and do not have the patience to sign up and sign in with our email and password first. We might also just want to try out the application and do not want the burden of having to create a new account just for that.

At the same time, the owners of the application need to know how many users their application has, and will want to get feedback about who’s using the application and how. To get these statistics, they need users to sign up with their emails.

These two situations put both the users and the app owners in a bit of a pickle. This is where having a Google login feature plays a very vital role.

Since Google is the most popular email platform in the world, allowing users to use Google login with your React app eliminates the friction between users and app owners. Users can begin using an application almost immediately without having to create a completely new account.

In this article, we’ll learn how the Google login works and how we can add it to our React app using the new Google Identity Services SDK called @react-oauth/google.

Jump ahead:

To follow along with this tutorial, you should have React installed on your local computer and be familiar with how to use it. If you have installed React, then you should already have Node.js, npm, and Yarn installed too.

Installing the required package to add Google login to your React app

To use the Google login, we’ll need to install the @react-oauth/google package. This is Google’s new Identity Services SDK; it allows us to integrate the Google login feature into our React app. Additionally, @react-oauth/google allows us to obtain the access tokens we need to access all Google APIs quickly and safely.

But, before we install and begin integrating the Google login into our React app, we’ll first need to get a Google client ID.

Acquiring a Google client ID for your project

A client ID is a unique identifier associated with an application that assists with client and server OAuth 2.0 authentication.

To get a client ID from Google, go to your Google Cloud Console and create a new project. For this article, I’ve named the project “Google Sign In,” but you can name it whatever you like:

Google Cloud Console With Prompt To Select A Project, Option To Create New Project, Search Bar For Projects And Folders, And Selected Google Sign In Project Under Recent Tab.

After creating a project, click on the project name and you’ll see a dashboard that looks like the one shown below. Your current project name should be visible at the top left of the dashboard, next to the Google Cloud logo:

Google Cloud Console Project Dashboard With Current Project Name Shown At Top Left And Left Side Menu For Apis And Services

Now, let’s review how to configure your consent screen before creating your credentials.

A consent screen, as the name suggests, is a consent page that prompts the user to use an external or third-party library to log in. This step alerts the user that they are leaving your app’s root page and allowing access to a third-party page.

Simply put, when you use OAuth 2.0 for authorization, your app requests that the user authorize one or more scopes of access from a Google Account. Scopes of access include any information or activities your app is allowed to access or exercise on the user’s account.

The Google login consent screen your app displays to the user may include a brief description of your project, its policies, and the requested scopes of access.

A simple consent page can look like this:

Simple Google Login Consent Page With Prompt To Choose An Account To Continue To App And Author's Account Shown As Option

To configure the Google consent page for your React app, go to the “OAuth consent screen” tab on the left-side menu of your Google Cloud Console.

Once you are in this tab, choose external — which is actually the only option you can choose unless you are using a Google-verified organization or application — and click the Create button to create your consent screen:

Google Cloud Console Project Dashboard With Oauth Consent Screen Options Displayed And External User Type Selected

Next, in the same tab, choose a name for your application and an email address to get notifications about any changes to your project. You can keep the other requirements and options empty for now. If you have the details ready, you can add them during this step if you want:

Google Cloud Console Project Oauth Consent Screen Registration With App Information Sections Including App Name And User Support Email Filled In

You can also skip the rest of the registration sections for now. Just scroll down in each section and click Save and continue until you are returned to the dashboard after completion.

Creating your web client ID

Next, on the left-side menu, click the Credentials tab to go to the page where you can create your web client ID.

On this page, click on CREATE CREDENTIALS at the top of the page, and then select the OAuth client ID option:

Google Cloud Console Dashboard With Credentials Option Selected In Left Side Menu And Dropdown Menu From Create Credentials Button With Option To Create Oauth Client ID.

You will be prompted to select an application type, as shown below. If you are following these steps for a React app, choose Web application (since we’re using the Google client ID for the web):

Step To Create Oauth Client Id Prompting Selection Of Application Type

If you are integrating it in a React Native, Flutter, or Swift application, you can choose the Android or iOS options for the two respective operating systems.

Next, we will choose a name for our client ID. This name is simply used to note or define the particular ID we are creating. So for example, if we are creating web, iOS, and Android IDs, we can include “Web ID,” “Android ID,” “iOS ID,” and so on in their naming convention to differentiate them.

Prompt To Add Oauth Client Id Name Within Google Cloud Console Dashboard

Next, we’ll also be adding two types of URLs: Authorized JavaScript origins and Authorized redirect URLs.

The Authorized JavaScript origins URL is the URL from which your application is originating the login; i.e., localhost and localhost:3000 for React developers, or your hosted URL if you’ve hosted your application.

The Authorized redirect URL is the link that Google will redirect the user to after the login is successful. For example, you may want to take the user back to your original link, or maybe redirect the user to another link. Either way, you have to include the URL here.

For the Authorized JavaScript origins and Authorized redirect URLs, add the localhost URLs: http://localhost:3000 and http://localhost, like so:

Google Cloud Console Authorized Origins URL Authorized Redirect URL

Finally, click the Create button to create your web client ID. You’ll be taken back to the homepage, where you’ll see your newly created credentials. Click the copy icon to copy your new web client ID:

Google Cloud Console Project Dashboard Homepage With Api Keys, Oauth 2.0 Client Ids, And Service Accounts Information

Now that we have successfully created our web client ID, let’s go into our React app, install it, and then integrate the Google login.

Putting it all together with @react-oauth/google

To use the Google login package, we first need to install it. Run either of the below commands to install the package:

npm install @react-oauth/[email protected]

yarn add @react-oauth/[email protected]

After installation, we’ll wrap our application with GoogleOAuthProvider and then supply our Google web client ID. This is so that our whole React app can access the Google Auth Provider once.

Inside our index.js file, we’ll wrap the application like so;


import React from 'react';
import ReactDOM from 'react-dom';
import { GoogleOAuthProvider } from '@react-oauth/google';
import App from './App';

    <GoogleOAuthProvider clientId="386932037035-k8v833noqjk7m4***********">
            <App />

Just like with every installed package in React, we must first import the module before we can use it. So inside your React app, go to the App.js file and copy the following code;


import React from 'react';
import { GoogleLogin } from '@react-oauth/google';

function App() {
    const responseMessage = (response) => {
    const errorMessage = (error) => {
    return (
            <h2>React Google Login</h2>
            <br />
            <br />
            <GoogleLogin onSuccess={responseMessage} onError={errorMessage} />
export default App;

The above code is a very simple way to showcase how to use the Google login. We imported the GoogleLogin module from @react-oauth/google and called it in our component. Next, we created two functions that console logs a response if the login was successful and an error if it wasn’t successful.

You can also combine the two functions into one and use a conditional to render it.

Here’s how the above code looks when we test it in the browser:

Image showing our Google login button in the UI

Clicking the Sign in with Google button will prompt a consent screen or modal that will look like this:

Popup Modal With Consent Screen Shown After Clicking Sign In With Google Button

Now that we have seen how to add the Google login to our React app, let’s take it a step further and get the user’s details to create a user profile in our app. We will only redirect the user to a homepage and then get the user’s email, name, and image.

Creating a user profile in your React app based on the user’s Google profile

Integrating Google login with our app gives us access to the user’s profile, which includes the user’s name, email address, image, accessToken, and so on. We’ll use this information to create our user profile.

Still, in our App.js component, let’s replace our existing code with this one below:


import React, { useState, useEffect } from 'react';
import { googleLogout, useGoogleLogin } from '@react-oauth/google';
import axios from 'axios';

function App() {
    const [ user, setUser ] = useState([]);
    const [ profile, setProfile ] = useState([]);

    const login = useGoogleLogin({
        onSuccess: (codeResponse) => setUser(codeResponse),
        onError: (error) => console.log('Login Failed:', error)

        () => {
            if (user) {
                    .get(`${user.access_token}`, {
                        headers: {
                            Authorization: `Bearer ${user.access_token}`,
                            Accept: 'application/json'
                    .then((res) => {
                    .catch((err) => console.log(err));
        [ user ]

    // log out function to log the user out of google and set the profile array to null
    const logOut = () => {

    return (
            <h2>React Google Login</h2>
            <br />
            <br />
            {profile ? (
                    <img src={profile.picture} alt="user image" />
                    <h3>User Logged in</h3>
                    <p>Name: {}</p>
                    <p>Email Address: {}</p>
                    <br />
                    <br />
                    <button onClick={logOut}>Log out</button>
            ) : (
                <button onClick={() => login()}>Sign in with Google 🚀 </button>
export default App;

In our code above, we imported googleLogout and useGoogleLogin from @react-oauth/google.

The useGoogleLogin API allows us to sign in to Google with a custom button. That is if we don’t want to use the GoogleLogin button that @react-oauth/google provides, we can style our preferred button and then use the useGoogleLogin API instead to make a login request to the clientId that we provided.

If the request is successful, we handle it in our onSuccess function that useGoogleLogin still provides, but if the request fails, we handle the error in our onFailure function.

Next, in our onSuccess function, we set our profile state with the data that was returned. This data contains the user’s details, like google_id, access_token, email, name, and so on. On any change in the user array, our useEffect hook will run and get the user details using the access token returned from Google login. User is a dependency to ensure that on any change in the user array i.e from null array to when we get the response from Google login, useEffect will be watching and then trigger accordingly.

Finally, we are using a conditional to change our UI: if the profile is true, the UI will show us the profile of the logged-in user with their image, name, and email. If the profile becomes null (i.e., when the user has logged out using the GoogleLogout button), it will show us the login button:

Cursor Shown Clicking Sign In With Google Button, Login Loading In Modal, And User Profile Being Generated From Google Information


Google login is an important feature to include in our applications to save time and improve the user’s experience. Another great reason to add this feature is that it is fast and easy to both implement and use.

In this tutorial, we reviewed how to add a Google login to our React application with @react-oauth/google. For another approach, learn about how you can use Firebase to handle Google authentication and sign in for your React apps.
I hope you found this article both easy to understand and helpful for your own projects.

Cut through the noise of traditional React error reporting with LogRocket

LogRocket is a React analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your React applications. LogRocket automatically aggregates client side errors, React error boundaries, Redux state, slow component load times, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to notify you of the most impactful problems affecting the most users and provides the context you need to fix it.

Focus on the React bugs that matter — .

Chimezie Innocent I am Chimezie, a software developer based in Nigeria. I am highly skilled in HTML, CSS, and JS to build web-accessible and progressive apps. I'm also skilled with React for web, React Native for Android apps, and Tailwind CSS. I write technical articles, too.

22 Replies to “The guide to adding Google login to your React…”

  1. thanks for the awesome tutorial.

    I have two questions.

    1. we never use the gapi instance in the code below useEffect( ). what is it for?

    2. When the user doesn’t get logged out after clicking logout. when trying to login, the data is stored, and the consent screen doesn’t show up. Any solutions?

    1. Thank you for your kind words.

      To answer your questions;
      1. gapi is simply used to interact or communicate with Google’s APIs one of which is the login Api that we are learning in this article.

      Gapi initializes our clientId and then loads it into our server-side application. We are calling it inside useEffect so that whenever our component renders or mounts, it gets called immediately.

      2. Yes, there is. You only need to add the consent prompt to your login button. See below;

      The prompt makes sure the consent screen shows up so you can select any account you want. Hope this answers your questions.

  2. hi innocent,
    thanks for putting this article up, it really awesome and helpful. I have a question for you, when I was trying to create my consent screen, the changes are not being saved, therefore, i could not proceed to create credentials. it kept on saying “An error saving your app has occurred”. Please, is there any way i can go about this.
    thanks in anticipation

    1. I’m glad you liked the article.

      For your question, I think the issue is because of the App name you are setting it to. It seems it’s not passing for some reason. So, since your project ID is a valid name, you should instead use that as your consent App Name. You can always change it later.

      In a case you don’t know where to find your project ID, simply click on the dropdown on the top bar of your console(where you can see your project name). When the dropdown opens, you should see your project ID on the same line of your project name. See first image of this article(the project ID for this article is nomadic-drummer-355219).

      Let me know in the comment if this fixes your issue.

  3. I just wanted to know how can I store the basic info of user in local storage, beacuse there is lot of info and I can’t get more info at a time.

    1. To save to local storage, you use localStorage.setItem(“user”, res) where “user” is the key you are saving your data as while res is the data you want to save. Both key and value must be strings in order to be saved in your local storage.

      You can save an object or array to your locaStrorage like this; localStorage.setItem(“user”, JSON.stringify(obj)) where you are converting the obj or array to a string.

      Check out this article to learn more about local storage,

  4. The tutorial is very awesome. Any link in Git? Thanks, you
    Any ideas, how Can I fix the belov issue.

    {type: ‘tokenFailed’, idpId: ‘google’, error: ‘server_error’}
    error: “server_error”
    idpId: “google”
    type: “tokenFailed”

    1. Thank you for bringing this to my notice, Omar. The article will be updated with the new migration.

    1. No, it’s not. @react-native-google-signin/google-signin is the package you need for react-native and it is easier to integrate too

    1. You’re correct, Vicee. profile.length would have been more suited for my use case. Thank you

Leave a Reply