How to Create Google Login using Google Auth API with React.js
Simple Steps to Add Google Sign-in with Google Auth API
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.
It is important to note that any app you sign up for by using your Google account automatically has access to your credentials(details).
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
The writer will be using Vite And Tailwind CSS
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 AccessClick on
NEW PROJECT
to create a new project-
give it any name of your choice and click on
CREATE
-
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
andCreate
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 Continue
Ignore 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.
Note: Without filling in the details on the OAuth Consent screen, you will not be able to generate credentials for your app.
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 URLDo the same for
Authorized redirect URLs
Click 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: ๐
import { useState } from 'react'
import './App.css'
function App() {
return (
<>
</>
)
}
export default App
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
orIndex.js
file, Imports theGoogleOAuthProvider
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>
<GoogleOAuthProvider clientId={import.meta.env.VITE_CLIENT_ID}>
: This line wraps the main application component (<App />
) with theGoogleOAuthProvider
component from@react-oauth/google
.clientId={import.meta.env.VITE_CLIENT_ID}
: This prop provides the Google Client ID for your application stored in.env
file. However, directly including it here is not recommended due to security concerns.
Creating a Google login button component
- Created a new file and named it
Login.jsx
under thesrc
folder
Import 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 theaxios
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 theuseGoogleLogin
hook from the@react-oauth/google
library. This library simplifies integrating Google Sign-In functionality into your React application. TheuseGoogleLogin
hook provides a way to trigger Google Sign-In and handle the user's response.import { FcGoogle } from "react-icons/fc"
: This line imports theFcGoogle
component from thereact-icons/fc
library. This library provides access to a collection of icons (including Google) that can be easily integrated into your React components. TheFcGoogle
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
functionconst 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); } }, });
This section uses the
useGoogleLogin
hook from the@react-oauth/google
library.It defines a function named
login
that will be triggered by a button clickInside the
login
function:The
onSuccess
the callback function is defined. This function will be executed if the Google Sign-In process is successful.Within the
onSuccess
callback:axios.get
is used to make a GET request to the Google endpoint "https://www.googleapis.com/oauth2/v3/userinfo". This endpoint provides information about the logged-in user.The request includes an Authorization header with the user's access token retrieved from the
response
object provided byuseGoogleLogin
.The response data (user information) is stored in the
res
variable usingawait
since the request is asynchronous.The
console.log(res.data)
line (for demonstration purposes) logs the user data to the console.(This will be replaced with logic to utilize the user information in your application (storing it in state)in part two of this tutorial)
An error-handling mechanism is implemented using a
try...catch
block. If any errors occur during the process, they are caught and logged into the console usingconsole.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.A
div
element is used as the container. It uses TailwindCSS classes for layout and styling (flex justify-center items-center my-[300px]
).Inside, a button element is created.
The
onClick
handler of the button is set to thelogin
function, triggering the Google Sign-In process when clicked.The button styles are defined using a TailwindCSS class (
flex bg-black rounded-xl
).The
FcGoogle
component fromreact-icons/fc
is used to render the Google icon. Inline styles are applied to adjust the icon size and spacing (fontSize: "30px", marginRight: "10px"
).The button text "Login with Google" is displayed.
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 dev
Click on the Localhost to open the local server
click on the button, sign in by adding your Google account and accept the condition
After accepting the condition, go to your browser console to see your Google account details
Remember we log the user data in the console using
console.log(res.data)
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.