How To Implement Google Authentication In React-JS

Hello Developers, In this blog we are going to learn how we can implement Google Authentication in React-JS

First of all, we need to create clientID and set up Google Cloud Console

Then click on Select project

Now click on New project:

Then choose the project name as per your choice

Now click on Credentials from the sidebar:

Then click on create Credentials Button and select OAuth client ID option

After clicking on OAuth client ID button click on Configure Consent screen button

Then you will be redirected to this screen:

Select external user type and click on create button

Now you will be redirected to this page

Then fill out all the required informations like your app name, app logo and a valid email address and click on save and continue

Now again go to credentials click on create credentials and OAuth client ID then select web application in application type

Then provide Authorized Javascript origins and Authorized redirect URL and click on Create button

Now a popup will be open on your screen like this

We will use this client ID later

That’s it, now create a new app using the following command

npx create-react-app google-auth-login

Then install following package in your app

npm install @react-oauth/google

Then import this package in your component

import 'primereact/resources/primereact.css';
import 'primeflex/primeflex.css';
import React from 'react';
import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google'

const GoogleAuth= () => {
  const responseGoogle = (response) => {
    console.log(response);
  }
  return (
    <div className="card flex justify-content-center">
      <GoogleOAuthProvider
        clientId='YOUR_CLIENT_ID'
        onScriptLoadError={responseGoogle}
        onScriptLoadSuccess={responseGoogle}
      >
        <GoogleLogin onSuccess={responseGoogle} onError={responseGoogle}></GoogleLogin>
      </GoogleOAuthProvider>
    </div>
  )
}

export default GoogleAuth

Make a function to get response after user successfully logged in

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories