Enable Dark Mode!
how-to-implement-google-sign-in-in-react.jpg
By: Alan Joy

How to Implement Google Sign-In in React

Technical Odoo 18

Authentication is a key part of modern web applications. Users want a fast and secure way to log in, and developers want a method that’s easy to implement and maintain. One popular approach is social authentication, and Google Sign-In is a top choice due to its simplicity and wide user base.

In this guide, we’ll walk you through how to implement Google Sign-In in a React app, even if you're a beginner. We’ll use the latest React practices and keep the code clean and easy to follow.

Why Use Google Sign-In?

Using Google Sign-In has several advantages:

* Familiarity: Users are more likely to log in using an account they already have.

* Security: Google handles password management and security.

* Convenience: Fast, one-click sign-in without creating a new account.

* Developer Support: Google provides robust tools and documentation.

Step 1: Create a Google Cloud Project and OAuth Client ID

First, we need to generate credentials from the Google Cloud Console.

1. Go to Google Cloud Console.

2. Click on Select a project > New Project.

3. Give it a name and click Create.

4. Once created, go to APIs & Services > Credentials.

5. Click + Create Credentials > OAuth 2.0 Client IDs.

6. Choose Web Application as the application type.

7. Under Authorized JavaScript origins, add:

http://localhost:3000

8. Click Create. You’ll receive a Client ID — copy this, as you’ll need it soon.

Step 2: Set Up the React App

If you haven’t already, create a new React project:

npx create-react-app google-signin-demo
cd google-signin-demo

Install the required package:

npm install @react-oauth/google

This is the official Google OAuth library for React.

Step 3: Wrap Your App with GoogleOAuthProvider

In your src/index.js (or main.jsx if using Vite), wrap your app with the GoogleOAuthProvider and provide your client ID:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { GoogleOAuthProvider } from '@react-oauth/google';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID">
    <App />
  </GoogleOAuthProvider>
);

Replace "YOUR_GOOGLE_CLIENT_ID" with the client ID you got from Google Cloud Console.

Step 4: Add the Google Login Button

In App.js, import and use the GoogleLogin component:

import React from "react";
import { GoogleLogin } from "@react-oauth/google";
import { jwtDecode } from "jwt-decode";
function app() {
  const handleSuccess = (credentialResponse) => {
    const decoded = jwtDecode(credentialResponse.credential);
    alert(`Signed in as ${decoded.name || decoded.email}`);
  };
  const handleError = () => {
    alert("Login Failed");
  };
  return (
    <div
      style={{
        margin: "100px",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
      }}
    >
      <h1>React Google Sign-In</h1>
      <GoogleLogin onSuccess={handleSuccess} onError={handleError} />
    </div>
  );
}
export default app;

We’re also using jwt-decode to decode the token received from Google into a readable user profile.

Install it:

npm install jwt-decode

Step 5: Test It Out

Run the development server:

npm start

You should see a “Sign in with Google” button. Click it, sign in, and check your browser console — it will print your name, email, and profile picture.

Optional: Display the User Info

You can take it a step further and display the user’s profile:

import React, { useState } from "react";
import { GoogleLogin } from "@react-oauth/google";
import { jwtDecode } from "jwt-decode";
function App() {
  const [user, setUser] = useState(null);
  const handleSuccess = (credentialResponse) => {
    const decoded = jwtDecode(credentialResponse.credential);
    setUser(decoded);
  };
  const handleError = () => {
    alert("Login Failed");
  };
  return (
    <div
      style={{
        margin: "100px",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
      }}
    >
      <h1>React Google Sign-In</h1>
      {user ? (
        <div>
          <img
            src={user.picture}
            alt="Profile"
            style={{ borderRadius: "50%" }}
          />
          <h2>Welcome, {user.name}</h2>
          <p>{user.email}</p>
        </div>
      ) : (
        <GoogleLogin onSuccess={handleSuccess} onError={handleError} />
      )}
    </div>
  );
}
export default App;

Now, your app will show the user's profile picture and email after login.

To read more about How to Set Up Typescript in a React Project, refer to our blog How to Set Up Typescript in a React Project.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message