In this tutorial, we will learn how to Login with Google Account using React app and php mysqli. Scroll down to the end of the page to you can see the YouTube video(CodeAT21) and GitHub repository full source code available for this.

The web developers can easily develop the Login with Google Account. we’ll provide the setup guide to developing login and register with Google account using php and store the google account user information in the MySQLi database. It is secure.

Login with Google Account using React and Node.js

Create Google API Console Project

  • Go to the Google API Credentials page. (or) create a new project and follow these steps
  • Click on OAuth consent screen > Choose external. Google will ask > app’s name, email, logo, domain name and some developer contact details.
  • Click on Create Credentials and select > "OAuth client ID."
  • Next, Select the web application type and add your website URL.
  • Click the Create button.

Setup

First, we'll create the react project and install the react-google-login npm packages. In open your system terminal/command line enter the code below :

npx create-react-app google-login
cd google-login
npm install --save react-router-dom
npm install axios
npm install react-google-login 
npm install --save react-toastify
npm start 

Next, Project structure your folder as follows.

src
├── components
|   ├── Dashboard.js
|   ├── GoogleLogin.js
|   └── Home.js
├── App.js
├── index.css
└── index.js 

Next, open up the App.js file located in the src folder. You should see this:

App.js
import React from 'react'; import {BrowserRouter as Router,Switch,Route} from "react-router-dom"; import { ToastContainer} from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import Home from './components/Home'; import Dashboard from './components/Dashboard'; function App() { return ( <div className="App"> <ToastContainer /> <Router basename="/"> <Switch> <Route exact path="/" component={Home}/> <Route path="/Dashboard" component={Dashboard}/> </Switch> </Router> </div> ); } export default App;
components/Dashboard.js
import React from 'react'; import { useGoogleLogout } from 'react-google-login'; import { useHistory } from "react-router-dom"; import { toast} from "react-toastify"; const clientId = '******* OAuth Client ID ***********'; const Dashboard = () => { let history = useHistory(); const onLogoutSuccess = () => { toast.success('Logged out Successfully', {position: "top-center",autoClose: 5000,hideProgressBar: false, closeOnClick: true,pauseOnHover: true,draggable: true,}); localStorage.removeItem('loginID'); history.push('/'); }; const onFailure = (res) => { console.log('Login failed: res:', res); }; const { signOut } = useGoogleLogout({ clientId, onLogoutSuccess, onFailure, }); return ( <div> <h1> Dashboard </h1> <h4> Insert Id : {JSON.parse(localStorage.getItem('loginID'))} </h4> <button onClick={signOut} className="gr__log__button">Logout</button> </div> ) } export default Dashboard
components/GoogleLogin.js
import React from 'react'; import { useGoogleLogin } from 'react-google-login'; import { useHistory } from "react-router-dom"; import { toast} from "react-toastify"; import axios from 'axios'; const clientId = '******* OAuth Client ID ***********'; const GoogleLogin = (props) => { let history = useHistory(); const onSuccess = async (res) => { console.log('Google Login Name', res.profileObj); axios.post(`http://localhost/api/loginGoogle.php`, { email: res.profileObj.email, familyName: res.profileObj.familyName, givenName: res.profileObj.givenName, googleId: res.profileObj.googleId, imageUrl: res.profileObj.imageUrl, name: res.profileObj.name, }) .then(res => { if(res.data.success === true){ console.log(res.data.usersid); localStorage.setItem('loginID',JSON.stringify(res.data.usersid)); toast.success('Login Successfully', {position: "top-center",autoClose: 5000,hideProgressBar: false, closeOnClick: true,pauseOnHover: true,draggable: true,}); history.push('/Dashboard'); } if(res.data.success === false){ toast.error(res.data.msg, {position: "top-center",autoClose: 5000,hideProgressBar: false, closeOnClick: true,pauseOnHover: true,draggable: true,}); } }) }; const onFailure = (res) => { console.log('Login failed: res:', res); }; const { signIn } = useGoogleLogin({ onSuccess, onFailure, clientId, isSignedIn: true, accessType: 'offline', }); return (<> <button onClick={signIn} className="gr__button"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48px" height="48px"><path fill="#FFC107" d="M43.611,20.083H42V20H24v8h11.303c-1.649,4.657-6.08,8-11.303,8c-6.627,0-12-5.373-12-12c0-6.627,5.373-12,12-12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C12.955,4,4,12.955,4,24c0,11.045,8.955,20,20,20c11.045,0,20-8.955,20-20C44,22.659,43.862,21.35,43.611,20.083z"/><path fill="#FF3D00" d="M6.306,14.691l6.571,4.819C14.655,15.108,18.961,12,24,12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C16.318,4,9.656,8.337,6.306,14.691z"/><path fill="#4CAF50" d="M24,44c5.166,0,9.86-1.977,13.409-5.192l-6.19-5.238C29.211,35.091,26.715,36,24,36c-5.202,0-9.619-3.317-11.283-7.946l-6.522,5.025C9.505,39.556,16.227,44,24,44z"/><path fill="#1976D2" d="M43.611,20.083H42V20H24v8h11.303c-0.792,2.237-2.231,4.166-4.087,5.571c0.001-0.001,0.002-0.001,0.003-0.002l6.19,5.238C36.971,39.205,44,34,44,24C44,22.659,43.862,21.35,43.611,20.083z"/></svg> <span className="buttonText">{props.text} </span> </button> </> ) } export default GoogleLogin
components/Home.js
import React from 'react' import GoogleLogin from "./GoogleLogin"; const Home = () => { return ( <div> <h1>Login with Google Account using React and Node.js</h1> <div className="wrapper"> <GoogleLogin text={"Log in with Google"}/> </div> </div> ) } export default Home

MySQL database

In the following example, we will start how to React wysiwyg text editor into the MySQL database using Node js.

  • Database Name – codeat21
  • Table Name – users
codeat21
CREATE TABLE `users` ( `users_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `givenName` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `imageUrl` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `familyName` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `date` datetime NOT NULL, PRIMARY KEY (`users_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Next, php project structure your folder as follows.

api
├── db_connection.php
└── loginGoogle.php 
db_connection.php
<?php header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: access"); header("Access-Control-Allow-Methods: POST"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); $db_conn = mysqli_connect("localhost", "root", "", "codeat21"); // Check connection if($db_conn === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } error_reporting(E_ALL); ini_set('display_errors','Off'); ?>
loginGoogle.php
<?php require 'db_connection.php'; // POST DATA $data = json_decode(file_get_contents("php://input")); if(isset($data->email) && isset($data->googleId) && isset($data->name) && !empty(trim($data->email)) && !empty(trim($data->googleId)) && !empty(trim($data->name)) ){ $email = mysqli_real_escape_string($db_conn, trim($data->email)); $familyName = mysqli_real_escape_string($db_conn, trim($data->familyName)); $givenName = mysqli_real_escape_string($db_conn, trim($data->givenName)); $googleId = mysqli_real_escape_string($db_conn, trim($data->googleId)); $imageUrl = mysqli_real_escape_string($db_conn, trim($data->imageUrl)); $name = mysqli_real_escape_string($db_conn, trim($data->name)); $login = mysqli_query($db_conn,"SELECT * FROM users WHERE email='$email' AND password='$googleId' "); if(mysqli_num_rows($login) > 0){ $row = mysqli_fetch_array($login); echo json_encode(["success"=>true,"usersid"=>$row['users_id']]); return; } else { $date = date('Y-m-d H:i:s'); $insertUser = mysqli_query($db_conn,"INSERT INTO `users`(name,email,password,givenName,imageUrl,familyName,date) VALUES('$name','$email','$googleId','$givenName','$imageUrl','$familyName','$date')"); if($insertUser){ $last_id = mysqli_insert_id($db_conn); echo json_encode(["success"=>true,"usersid"=>$last_id]); return; }else{ echo json_encode(["success"=>false,"msg"=>"User Not Inserted!"]); return; } } } ?>