How to Integrate Google OAuth in a React 18 App
Integrating Google OAuth into your project is an easy way for users to sign in and access the app with just their Google account. I know this might sound daunting but I promise you, it’s not. If you are familiar with API calls then this should be a walk in the park but if you’re not, “You are the reason I am here“.
In this guide, I will be showing you how to add Google OAuth to your React project using the modern and compatible @react-oauth/google
package. If you are still using gapi-script
, you need a change!
Why Use @react-oauth/google
?
Unlike the older react-google-login
, this library is actively maintained and fully compatible with React 18. It simplifies the OAuth process and handles Google’s authentication protocols seamlessly, removing the need for external dependencies like gapi-script
.
Step 1: Set Up Google OAuth Credentials
First, You need to set up a Client ID on Google Clou Console. Here is how you can do that:
Go to the Google Cloud Console.
You need to create an account if you don’t have one
Then click on APIs & Services.
on the sidebar, click on Credentials.
Click on the “Create Credentials“ button at the top of the newly displayed tab. Click it and select OAuth 2.0 Client IDs.
Pick “Web Application“ since you are using React.
Under Authorized JavaScript origins, add your app’s domain (e.g.,
http://localhost
for local development). For React, the default URL is localhost:3000.Copy your Client ID.
Now we can move to the next phase of this guide
Step 2: Install Dependencies Using Your Terminal
Now, it’s time to interact with your project terminal. You should have finished setting up your project folder by now. If you don’t know how or are having issues setting up your project environment, check out my article “Getting Started with React.”
open your terminal
cd to your project directory
Input this command and click enter to install the Google OAuth library in your project.
npm install @react-oauth/google
This library provides everything you need to implement Google OAuth.
Step 3: Initialize the GoogleOAuthProvider
Component in Your JSX File
Before we go into the logical part of this section, I want to point out that this guide should not dictate how your project is structured.
As a developer, you need to only understand the syntax and how things works. Be creative, be curious and play around with your code base as much as possible.
Alright, now we can move on to initialize Google OAuth, wrap your application in the GoogleOAuthProvider
component and pass your Client ID.
Edit your index.js
or App.js
file:
// index.js or App.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleOAuthProvider } from '@react-oauth/google';
import App from './App';
const clientId = "YOUR_GOOGLE_CLIENT_ID";
ReactDOM.createRoot(document.getElementById('root')).render(
<GoogleOAuthProvider clientId={clientId}>
<App />
</GoogleOAuthProvider>
);
Replace YOUR_GOOGLE_CLIENT_ID
with the actual Client ID from the Google Cloud Console.
Step 4: Add a Google Login Button
In your App.js
or any component, use the GoogleLogin
component provided by the library to enable the login functionality.
// App.js
import React from 'react';
import { GoogleLogin } from '@react-oauth/google';
const App = () => {
const handleLoginSuccess = (credentialResponse) => {
console.log('Google Sign-In Successful:', credentialResponse);
// Decode the JWT to access user details
};
const handleLoginError = () => {
console.error('Google Sign-In Failed');
};
return (
<div>
<h1>React 18 Google OAuth</h1>
<GoogleLogin
onSuccess={handleLoginSuccess}
onError={handleLoginError}
/>
</div>
);
};
export default App;
onSuccess
: Handles the successful login response.onError
: Handles any errors during the login process.
Step 5: Decode the JWT for User Information
Google returns a JWT (JSON Web Token) on successful login. You can decode this token to access user details.
Install a library like jwt-decode
:
npm install jwt-decode
Then use it in your success handler:
import jwt_decode from "jwt-decode";
const handleLoginSuccess = (credentialResponse) => {
const user = jwt_decode(credentialResponse.credential);
console.log("Decoded User Info:", user);
};
The user
object will contain details like the user’s email, name, and profile picture.
Key Differences from react-google-login
No
gapi-script
Needed: The new library handles all script loading internally.JWT Instead of
profileObj
: Unlikereact-google-login
, which provided aprofileObj
this library returns a JWT credential. You can decode it for user information.
Conclusion
Following this guide, you can set up Google OAuth in your React 18 app quickly and effectively. The @react-oauth/google
library provides a modern, secure, easy-to-use solution for integrating Google authentication into your project.
Refer to the official documentation for more advanced setups, such as logging out users or refreshing tokens.
Feel free to reach out with questions or share your implementation challenges!