How to add Google Login to a React app

Alex
9 min readMar 12, 2023

Hi, in this tutorial I will show you how to implement Google account login functionality into your React application.

Introduction

When building applications there are instances where you may want to let your users login to your application in order to use it, however, this may mean you need to build a big piece of functionality that will involve email and password submission which can be time-consuming and cumbersome. Luckily, companies like Facebook, Twitter and Google have built packages that enable us (very clever) developers to allow users to login to our applications using their already existing social media accounts, saving us the time of building additional code and saving the user from having to create yet ANOTHER account to use a website. For this tutorial, I will be going through how to login to your Google account using a react package named the below.

@react-oauth/google

Which is Googles Identity Services SDK.

Google Cloud Console

However, before we build our React application we need to navigate to Google Cloud console and build a project as well as create a client ID that will be used with the package.

Firslty, navigate to the url below.

Now, click the dropdown to the right of the “Google Cloud” logo/icon and click “New Project” on the pop up.

Give your project a relevant name such as “mygooglelogin” app and leave the “Location” dropdown as it is.

Now click “Create”

After about 30–60 seconds the project should be created and you can select it from the dropdown on the left hand side.

Afterwards, click on the hamburger menu on the top left hand side and from the sidebar that pops out click on “APIs & Services” and then within the menu click on “OAuth consent screen”.

Under the “User Type” options click on “external” and then click on “Create”.

A screen asking you to enter an app name and email address will appear. For now, only fill out the app name and email address text boxes and then scroll down further and click “Save and continue”. The other text boxes that we haven’t filled in are mainly for if you have a website ready and want to enter the URL of the website/privacy policy.

NOTE: Try to not have the word “Google” in the app name, this may have just been an error on my end, but the console failed to create the app consent screen when i had Google in the name, i removed it and the “Save and Continue” worked fine.

Next, a screen will show asking for test users, just click “Save and Continue”.

Congratulations, we are now with the OAuth consent screen registration, we will now move on and create the Client ID. So now click on the “Credentials” page on the sidebar.

Click on the button labelled “Create Credentials” and from the options that appear click “OAuth Client ID”.

In the “Application Type” dropdown choose “Web application” because we are using React, however, if you were using React-Native/Flutter/ Swift you should choose Android/iOS.

Give your client ID a name such as “React Web Google Login ID” or something similar and maybe not as long.

The next heading is “Authorized JavaScript Origins” which is the HTTP origins that host your application so ours will be localhost and localhost:3000.

The heading after is “Authorised Redirect URIs” which is the url the application will redirect to after the user has logged in with their Google account.

So again, the Authorised Redirect URIs values will be localhost:3000 and localhost.

After adding these values click save, meanwhile, a popup screen should show with your newly created client ID and client secret, there should be an option to download them as json but just keep them safe and at hand as we will need the client ID.

React

So now that we have created the client ID for our app, we now need to make… our app.

Now navigate to the location you want your React project to be using a terminal (which can be within your favoured code editor such as VS Code) and enter the below command.

npx create-react-app googleloginproject

After the project has been created open it in your code editor and run the below command.

npm install @react-oauth/google@latest

When this has finished installing we need to open the file “index.js” in order to wrap the whole application with the Google OAuth Provider so every subsequent page in our application can access it.

You will need to import “GoogleOAuthProvider” from “react-oauth/google”

Now wrap this component around the “StrictMode/App” component like below. A required parameter for this component is the client ID you just created in Gooel Cloud Console, so paste that here.

Fantastic, now that we have done this we need to navigate to the App.js file and import the Google Login button component for us to use it.

We will now need create 2 small functions in App.js in order to console.log out either the success response or error response when we login to the application.

 const responseOutput = (response) => {
console.log(response);
};
const errorOutput = (error) => {
console.log(error);
};

After creating those 2 functions change the code inside the return to the below. See how we are using the GoogleLogin component along with passing in the 2 functions we created as parameters.

<div>
<h2>React Google Login</h2>
<br />
<br />
<GoogleLogin onSuccess={responseOutput} onError={errorOutput} />
</div>

You should now start up your application and it should look similar to the below.

When you click the button a popup should show asking you to login with one of your Google accounts, once you have selected one of these a page should show asking you to confirm that you want to sign in to the application you have made with that account. The popup should close and you are now logged in (however I had to refresh the page for this to happen but i think it was something on my behalf), remember to check the console for what the output was.

If the response is successful then an object should be present in the console containing 3 properties. A client ID, credential and selectBy.

Since we are now logged in we have access to the users name, email address and profile picture which we can print out on to the screen.

In addition to using the default Google Login button, we can also use a custom button that performs the same functionality.

To get the user info we will need to make a request to an API url which we will use axios to do.

So enter the following command to install it.

npm install axios

Now import it at the top of “App.js”

import axios from 'axios';

We now also need to import “googleLogout” and “useGoogleLogin” from our React oauth Google app.

So our import looks like this.

import { GoogleLogin, googleLogout, useGoogleLogin } from '@react-oauth/google'

“useGoogleLogin” enables users to sign in to Google with a custom button so it gives us more freedom than just using the generic GoogleLogin button. There are 2 functions which useGoogleLogin provides named “onSuccess” and “onFailure”.

We also need to create 2 state objects, one named “userInfo” which will hold the access token and another named “profileInfo” like below which will hold the data we get back from the axios API call.

const [userInfo, setUserInfo] = useState([]);
const [profileInfo, setProfileInfo] = useState([]);

In addition, we will need a function that handles logging in since we are now using a custom button.

Name the function “login” and set it equal to “useGoogleLogin” with the 2 functions set as below.

const login = useGoogleLogin({
onSuccess: (response) => setUserInfo(response),
onError: (error) => console.log(`Login Failed: ${error}`, )
});

On the successful call of “useGoogleLogin” we will take the response from the server and set it to be inside of an array in the state “userInfo”.

Furthermore, we will also need a logout function which sets the profile information to null and also logs out of the account which is done with “googleLogout” that we imported earlier.

const logOut = () => {
googleLogout();
setProfileInfo(null);
};

The next piece of code is the most complicated.

We will use a hook named “useEffect” in order to run this whenever the component is rendered, inside of the “useEffect” we will first check if the user is true/has information inside of it.

If so, we will use axios to call the Google OAuth2 APIs in order to retrieve information about the user based on the access_token that was retrieved from the response when logging in.

There are 2 headers attached to the request, one being “Authorization” which contains a bearer token (being the access_token) as it sending the request to a protect resource and needs the access token to verify the request is legitimate. The second header is to indicate which content type the client can understand. In this instance it is application/json.

If the response of this call is successful then we set the response data equal to the ProfileInfo state and if there is an error we console.log it. In other applications there would usually be an error state that would show the error message on the screen in order to handle it gracefully. In addition, we use the “userInfo” state as a dependency array on useEffect, so whenever “userInfo” is changed the below code re-runs.

useEffect(
() => {
if (userInfo) {
axios
.get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${userInfo.access_token}`, {
headers: {
Authorization: `Bearer ${userInfo.access_token}`,
Accept: 'application/json'
}
})
.then((response) => {
setProfileInfo(response.data);
})
.catch((error) => console.log(error));
}
},
[ userInfo ]
);

We now need to look at the code within the “return” statement.

Add some curly braces and first check if “profileInfo” is true, meaning there is data inside of it then we output the information that was set in the “profileInfo” state which is values such as profile picture, name and email.

Display this information appropriately and also display a logout button which runs the “logout” function when clicked.

If the “profile” is not true then that means we are not logged in and so display a button that runs the “login” functionality to login the user.

{profileInfo ? (
<div>
<img src={profileInfo.picture} alt="Profile Image" />
<h3>Currently logged in user</h3>
<p>Name: {profileInfo.name}</p>
<p>Email: {profileInfo.email}</p>
<br />
<br />
<button onClick={logOut}>Log out</button>
</div>
) : (
<button onClick={()=>login()}>Sign in</button>
)
}

So now my page looks like the below.

After I clicked “Log out”.

The code has determined that userInfo is true, takes the access token from userInfo state and applies that to an API call to the OAuth2 API, if the response from this API call is successful then the profileInfo state is set with the response including the image, email and name.

Thank you for reading this article, I hope you learned something from this, I definitely did and will incorporate this into my own React projects in the future.

--

--