In this tutorial, we will learn how to Login with Google Account using React app and Node/Express API. 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 Node js and store the google account user information in the MySQLi database. It is secure.

Login with Google Account using React and PHP

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:8080/loginGoogle`, { 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, Node js project structure your folder as follows.

├── config
|  ├── database.js	
├── index.js
├── package.js
└── package-lock.js 
database.js
const util = require('util'); const mysql = require('mysql2'); const pool = mysql.createPool({ connectionLimit: 10, host : 'localhost', user : 'root', password : '', database : 'codeat21' }); // Ping database to check for common exception errors. pool.getConnection((err, connection) => { if (err) { if (err.code === 'PROTOCOL_CONNECTION_LOST') { console.error('Database connection was closed.'); } if (err.code === 'ER_CON_COUNT_ERROR') { console.error('Database has too many connections.'); } if (err.code === 'ECONNREFUSED') { console.error('Database connection was refused.'); } } if (connection) connection.release(); return; }); // Promisify for Node.js async/await. pool.query = util.promisify(pool.query); module.exports = pool;
index.js
const express = require('express'); const app = express(); const path = require('path'); const cors = require('cors'); const bodyParser = require('body-parser'); const port = process.env.PORT || 8080; // Databse Connection const db_connection = require('./config/database').promise(); app.use(cors()); app.use(bodyParser.json() ); app.use(bodyParser.urlencoded({extended:true})); app.post('/loginGoogle', async (req, res) => { try { let date_today = new Date(); const [sql] = await db_connection.execute("SELECT * FROM users WHERE email = ? AND password = ?",[req.body.email, req.body.googleId]); if (sql.length > 0) { return res.status(200).json({success: true, usersid:sql[0].users_id}); }else { const [rows] = await db_connection.execute("INSERT INTO `users` (`name`,`email`,`password`,`givenName`,`imageUrl`,`familyName`,`date`) VALUES(?, ?, ?, ?, ?, ?, ?)",[req.body.name,req.body.email,req.body.googleId,req.body.givenName,req.body.imageUrl,req.body.familyName,date_today]); if (rows.affectedRows === 1) { return res.json({ success: true, usersid:rows.insertId}) } } } catch (err) {console.log(err)} }); app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))