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:
- Installing the required package to add Google login to your React app
- Acquiring a Google client ID for your project
- Configuring a Google login consent screen for your React app
- Creating your web client ID
- Putting it all together with
@react-oauth/google
- Creating a user profile in your React app based on the user’s Google profile
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:
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:
Now, let’s review how to configure your consent screen before creating your credentials.
Configuring a Google login consent screen for your React app
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:
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:
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:
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:
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):
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.
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:
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:
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 npm install @react-oauth/[email protected] //Yarn 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;
/*index.js*/ import React from 'react'; import ReactDOM from 'react-dom'; import { GoogleOAuthProvider } from '@react-oauth/google'; import App from './App'; ReactDOM.render( <GoogleOAuthProvider clientId="386932037035-k8v833noqjk7m4***********.apps.googleusercontent.com"> <React.StrictMode> <App /> </React.StrictMode> </GoogleOAuthProvider>, document.getElementById('root') );
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;
/*App.js*/ import React from 'react'; import { GoogleLogin } from '@react-oauth/google'; function App() { const responseMessage = (response) => { console.log(response); }; const errorMessage = (error) => { console.log(error); }; return ( <div> <h2>React Google Login</h2> <br /> <br /> <GoogleLogin onSuccess={responseMessage} onError={errorMessage} /> </div> ) } 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:
Clicking the Sign in with Google button will prompt a consent screen or modal that will look like this:
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:
/*App.js*/ 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) }); useEffect( () => { if (user) { axios .get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${user.access_token}`, { headers: { Authorization: `Bearer ${user.access_token}`, Accept: 'application/json' } }) .then((res) => { setProfile(res.data); }) .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 = () => { googleLogout(); setProfile(null); }; return ( <div> <h2>React Google Login</h2> <br /> <br /> {profile ? ( <div> <img src={profile.picture} alt="user image" /> <h3>User Logged in</h3> <p>Name: {profile.name}</p> <p>Email Address: {profile.email}</p> <br /> <br /> <button onClick={logOut}>Log out</button> </div> ) : ( <button onClick={() => login()}>Sign in with Google 🚀 </button> )} </div> ); } 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:
Conclusion
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.

Focus on the React bugs that matter — try LogRocket today.
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?
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.
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
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.
thanks it helped
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.
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,https://blog.logrocket.com/localstorage-javascript-complete-guide/
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”
The package react-google-login was deprecated!
Thank you for bringing this to my notice, Omar. The article will be updated with the new migration.
Okay, Thank you… Please when should we expect it?
I’m only seeing this now. It has been updated
Is it the same for React-Native?
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
I think you need to use useState(null) instead of useState([]) to make this logic work.
You’re correct, Vicee. profile.length would have been more suited for my use case. Thank you
Hey there, this npm package is not from Google correct? https://www.npmjs.com/package/@react-oauth/google is developed by a third-party author
yes, it’s from a third party author
Wow, very helpful. Thanks a lot.
You’re welcome. I’m glad you found it helpful.
I have one issue , can anyone help me? I have used above code but getting issues when deploying it to django server.
detailing issue posted on stackoverflow:-
https://stackoverflow.com/questions/76221019/reactjs-app-gmail-login-issue-when-deploy-on-django-server
how can i call google spread sheet api after login with google.