
Table of contents
Introduction
Before signing up or logging into any account can feel like a thorn in the flesh. There are so many details to input, and sometimes these registration processes can be time-consuming or lead to frustration. But have you ever wondered why this is the case?
To make things easier for users, Google introduced an Auth API to help streamline these lengthy registration processes to be as simple as clicking a button on any application, allowing you to get started right away.
Brief overview of Google Auth API
What is the Google Auth API? The Google Auth API is a service offered by Google to simplify the registration and login procedures on applications. It enables users to verify their identity by using their Google account details. If you have a Google account(Gmail), the login information you used to make your Gmail account will automatically apply when signing up for any app.
In this article, you will learn how to create a Google login with Google Auth API.
Prerequisite
knowledge in React.js hooks such
useState A text editor and browser
Install React using either Create React app or Vite
Know how to use CSS frameworks
Required Packages
Setting up Google Auth API
Creating a project in the Google Cloud Console
Navigate to Google Cloud Console and Sign up using
Click on
APIs & Services under Quick Access Click on
NEW PROJECT to create a new project After creating your new project, open the project and click on
OAuth consent screen on the left-hand side of the page as seen belowπ Click on
External and Create as seen in the picture above πAdd your App information
a. Add your app name and User support Email, you can use your email or your company email.
b. You can add your App logo and App domain including links to privacy policy and term of use if any or ignore it
c. add your developer's contact information and Click on
Save and ContinueIgnore the Scope and Click on Save and Continue
Ignore Test Users and click on
Save and Continue Generating OAuth client ID and client secret
After creating your OAuth consent screen, you can now proceed to generate app credentials through these steps.
Click on
Credentials on the left side of your dashboard and click on + CREATE CREDENTIALS After clicking on + Create Credentials, you are going to see a popup, select
OAuth client ID Select any application type of your choice and add
Next, click on ADD URL under
Authorized Javascript Origins to add your local server port and custom URL Do the same for
Authorized redirect URLsClick on Save and you will see a pop-up that displays your client ID and client secretCongratulationson you've successfully generated your Client ID and Client Secret ππ
Setting up a new project in React.js
Creating a new project structure
After installing React, clear out the written code
App.jsx/js to have an empty file like this: πThis is where other components will be displayed. In part two of this lesson, the routing will happen here.
Installing necessary dependencies
Install all the required packages in your project. using the following command line
Axios :
npm i axios React Icons:
npm i react-icons React Oauth Google :
npm i @react-oauth/google To verify its installation, inspect the
package.json file to confirm if you have something like this πImplementing Google login in React.js
Creating an ENV file
Create an .env file in your project
Copy your Client ID from the cloud console under Credential
Store the ID to the variable
//FOR vite user
VITE_CLIENT_ID = //YOUR CLIENT ID
//for create-react-app user
REACT_APP_CLIENT_ID = //YOUR CLIENT ID
Wrapping App with Google OAuth Provider
Inside your
Main.jsx or Index.js file, Imports the GoogleOAuthProvider component from the @react-oauth/google library, which helps integrate Google OAuth functionality into your application. import { GoogleOAuthProvider } from '@react-oauth/google'
wrap your app with the Google OAuth Provider
<GoogleOAuthProvider clientId={import.meta.env.VITE_CLIENT_ID}>
{/* Components using Google OAuth */}
<App />
</GoogleOAuthProvider>
Creating a Google login button component
Created a new file and named it
Login.jsx under the src folderImport the following packages to the
Login.jsx import axios from "axios";
import { useGoogleLogin } from "@react-oauth/google";
import { FcGoogle } from "react-icons/fc";
import axios from "axios" : This line imports the axios library, a popular tool for making HTTP requests in JavaScript applications. It allows you to fetch data from APIs or servers.import { useGoogleLogin } from "@react-oauth/google": This line imports the useGoogleLogin hook from the @react-oauth/google library. This library simplifies integrating Google Sign-In functionality into your React application. The useGoogleLogin hook provides a way to trigger Google Sign-In and handle the user's response.import { FcGoogle } from "react-icons/fc" : This line imports the FcGoogle component from the react-icons/fc library. This library provides access to a collection of icons (including Google) that can be easily integrated into your React components. The FcGoogle component specifically renders the Google icon.Create a Functional component
const Login = () => {
// ... component logic
};
This line declares a functional React component named
Login. Functional components are a way to create reusable UI elements in React by defining a function that returns JSX (JavaScript XML) describing the UI structure.Integrate Google login inside the
Login function const login = useGoogleLogin({
onSuccess: async (response) => {
try {
const res = await axios.get(
"https://www.googleapis.com/oauth2/v3/userinfo",
{
headers: { Authorization: `Bearer ${response.access_token}` },
}
);
console.log(res.data);
} catch (err) {
console.log(err);
}
},
});
Button with Google Icon
return (
<div className="flex justify-center items-center my-[300px]">
<button onClick={login} className="flex bg-black rounded-xl">
<FcGoogle style={{ fontSize: "30px", marginRight: "10px" }} />
Login with Google
</button>
</div>
);
This section defines the JSX returned by the
Login component.Exporting the Component:
export default Login;
Import the Login component in your App. jsx file to render the component on the screen.
import Login from './Login'
function App() {
return (
<>
<Login />
</>
)
}
export default App
Result
open your terminal and run the following command
npm run devClick on the Localhost to open the local server
click on the button, sign in by adding your Google account and accept the condition
Conclusion
In conclusion, we have successfully implemented Google login using the Google Auth API in React.js. In the upcoming part two of this tutorial, we will utilize the user details obtained during the login process to create a dashboard for the user.
If you find this article helpful, please like, share, subscribe, and follow for more.
You can buy me a coffee.
0 likes Β· 65 views Β· Jul 15, 2024
Learn how to integrate Google login seamlessly into your React.js app using Google Auth API. Simplify user registration with ease