Editor’s note: This article was updated by Chimezie Innocent on 7 February 2024 to include information about integrating Google OAuth login into React components, as well as to incorporate information about handling authentication responses in a React app.
There are times when users want immediate access to an application without the hassle of creating and logging into a new account. At the same time, app owners want to know how many users their application has and require user registration for tracking and feedback purposes. 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.
Because Google (Gmail) 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 Google login works and how we can add it to our React app using the new Google Identity Services SDK called @react-oauth/google
.
To follow along with this tutorial, you should have:
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.
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.
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 allows 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 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 but if you have the details ready, you can add them during this step:
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.
After creating the OAuth consent screen, we need to publish the app before we can test it or before the authentication works. By default, its status is Testing and after publishing, it gets pushed to Production:
Once you have set your app status as “In production,” your app will be available to anyone with a Google Account.
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 (because 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 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 successful login. 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 into our React application.
To use the Google login package, we first need to install it. Run either of the following commands to install the package:
//Npm npm install @react-oauth/google@latest //Yarn yarn add @react-oauth/google@latest
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 log 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.
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 the following:
/*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. 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.
Handling authentication responses effectively is crucial for providing a seamless user experience in React applications. Whether the authentication fails or succeeds, you should handle it to inform users of the state of their requests.
If the request call 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.
Upon successful authentication, you may want to store the user data and redirect the user to a protected route. Conversely, in the case where authentication fails, we may want to notify the user that the login failed and then provide an alternative option for authentication.
From our example above, you can observe that inside our login function, we have two props: onSuccess
and onError
. In our onSuccess
function, we set our profile state with the returned data. This data contains the user’s details, like google_id
, access_token
, email, name, and so on.
See the code snippet below:
const login = useGoogleLogin({ onSuccess: (codeResponse) => setUser(codeResponse), onError: (error) => alert('Login Failed:', error) });
Similarly, 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. We added user
as a dependency in our useEffect
function 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:
Google login is an important feature to include in our applications to save time and improve user experience. Another great reason to add this feature is that it is fast and easy to 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 signin for your React apps.
I hope you found this article easy to understand and helpful for your projects.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.
33 Replies to "The guide to adding Google login to your React app"
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.
Thank you for this content, it was very helpful. You really explained every step to the last detail.
please change the code snippet with this “`await axios
.get(`https://www.googleapis.com/oauth2/v1/userinfo`, {
headers: {
Authorization: `Bearer ${tokenResponse.access_token}`,
Accept: ‘application/json’
}}
)“` we don’t need to provide access_token in url, it was giving me 401 so, i removed it
i got that error
Cross-Origin-Opener-Policy policy would block the window.closed call.
gq.C @ client:273
client:273 Cross-Origin-Opener-Policy policy would block the window.closed call.
gq.C @ client:273
so i have getting error of coop , i copy your entire process but getting the same error
Hi
i dont want to show the consent pop-up how to disable this pop-up
Thank you so much! 🙂
Perfect source of knowledge. Only one remark for TS users only:
onSuccess: (codeResponse) => setUser(codeResponse)
that line might suggest type CodeResponse for var codeResponse, while in fact it is TokenResponse
La forma en como maneja la obtenciĂłn de datos esta persona es interesante, evita hacer la llamada al API de Google para obtener la informaciĂłn del usuario.
You have provided goggle cloud link instead of developer console please check it asap.
good article: this is help me so much
Helpful, and educative article, nicely done, thank you my man.