Google Oauth With Node Js
Google Oauth With Node Js
js
Mayooran Navamany
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial uses permitted by
copyright law. Although the author/co-author and publisher have made every effort to ensure
that the information in this book was correct at press time, the author/co-author and publisher do
not assume and hereby disclaim any liability to any party for any loss, damage, or disruption
caused by errors or omissions, whether such errors or omissions result from negligence,
accident, or any other cause. The resources in this book are provided for informational purposes
only and should not be used to replace the specialized training and professional judgment of a
health care or mental health care professional. Neither the author/co-author nor the publisher
can be held responsible for the use of the information provided within this book. Please always
consult a trained professional before making any decision regarding the treatment of yourself or
others.
https://www.c-sharpcorner.com/ebooks/ 2
Table of Contents:
Introduction MERN stack Architecture ........................................................................................... 4
Implementing Google OAuth ......................................................................................................... 6
Apply the MERN Stack .................................................................................................................10
React Application ........................................................................................................................12
Node.js backend application. .......................................................................................................21
MongoDB Connection String ........................................................................................................26
Connect the API with MongoDB....................................................................................................29
Run the Application. ....................................................................................................................36
View the Database. .....................................................................................................................39
Login Data in GUI ........................................................................................................................41
https://www.c-sharpcorner.com/ebooks/ 3
1
Introduction MERN stack
Architecture
Overview
https://www.c-sharpcorner.com/ebooks/ 4
Introduction MERN stack Architecture
Welcome to the world of the MERN stack! This guide will cover the basics of MongoDB,
Express.js, React.js, and Node.js, along with interview tips. Whether a novice or an expert, you’ll
gain the knowledge to build robust web applications. Let’s dive in and explore the power of the
MERN stack!
https://www.c-sharpcorner.com/ebooks/ 5
2
Implementing Google
OAuth
Overview
https://www.c-sharpcorner.com/ebooks/ 6
Understanding Google OAuth (Open Authorization), in details.
The authorization process starts when your application redirects a browser to a specified Google
URL.
This URL contains query parameters that define the type of access being requested. Google
manages user authentication, session selection, and user consent. Upon completion, an
authorization code is provided, which the application can exchange for an access token and a
refresh token
https://www.c-sharpcorner.com/ebooks/ 7
Get the Google API key and Credentials
Step 01
Go to the Navigation Menu and click it. Open the side panel and Go to the APIs and services
Click it and go
to click Credentials.
Step 02
Step 03: Now you can see my exciting project “Student Management System”
https://www.c-sharpcorner.com/ebooks/ 8
Picture 05. Download The path in Credentials.
Click on the Download icon and get your OAuth client ID credentials in a JSON file. Go to the
API Key Click on the SHOW KEY button. And copy the API KEY.
Picture 06. Open the API KEY popup window and copy the API KEY.
https://www.c-sharpcorner.com/ebooks/ 9
3
Apply the MERN Stack
Overview
https://www.c-sharpcorner.com/ebooks/ 10
Above I shortly explain what the MERN stack is. Now I will apply Google OAuth how to work in
the MERN stack. You can see this diagram
Picture 07. See the integration of Google OAuth2 API, Node.js, Express, Passport, MongoDB,
and other packages
To implement Google OAuth in a MERN stack application, first integrate Google OAuth in the
React front end using @react-oauth/google to handle the authentication flow. Wrap your
application with GoogleOAuthProvider and use the GoogleLogin component to prompt users to
sign in. On successful login, retrieve the user token and send it to the Node.js backend via an
API request. In the Node.js server, verify the token using the Google API and extract the user
information. Then, check if the user exists in the MongoDB database; if not, create a new user
record. Finally, generate a session token for the authenticated user and manage it on the client
side for subsequent requests.
• REACT
• NODE and EXPRESS
• MONGODB
https://www.c-sharpcorner.com/ebooks/ 11
4
React Application
Overview
https://www.c-sharpcorner.com/ebooks/ 12
Create the New React application.
Now I’m going to create a new React project
Step 1: Go to the Command Prompt “ CMD Open the CMD, and type follow this command.
We successfully installed React JS and ran it. We are now implementing Google Auth in
React.js by installing the necessary packages.
• @react-oauth/google: Google OAuth2 using the new Google Identity Services SDK
• Axios: Promise-based HTTP client for the browser and node.js
• Jwt-decode: JSON Web Token can be decoded.
npm install @react-oauth/google axios jwt-decode
https://www.c-sharpcorner.com/ebooks/ 13
Picture 10. We are installing the necessary packages.
https://www.c-sharpcorner.com/ebooks/ 14
Login page
import React from "react";
I'm going to integrate the login.jsx and logout.jsx pages into the app.js file.
function App() {
return (
<div className="App">
<h1>Implementing Google OAuth in MERN</h1>
<div className="center">
<Login />
</div>
<div className="center">
<Logout />
</div>
</div>
);
}
Picture 13. Go to run the app. And see the view in the browser.
https://www.c-sharpcorner.com/ebooks/ 15
Let's create an env file.
• Go to the dotenv npm page. Install the npm package for dotenv for your node js
application.
• Create an env file in reactjs/ node-js. Do not create a js file. Name it. env.
• Go to the Client project create the ‘. env’ file and add Client-Id and API-key
The process for obtaining the OAuth client ID and API key is already explained in pictures 5 & 6.
https://www.c-sharpcorner.com/ebooks/ 16
GoogleOAuthProvider: This is a component from the @react-oauth/google library that wraps
around your application or a part of your application where you want to enable Google OAuth2
authentication.
<GoogleOAuthProvider clientId={CLIENT_ID}>
This component wraps the Google login functionality and takes a clientId prop, which is your
Google OAuth client ID.
<GoogleLogin />
Picture 15. See the view Google login button and logout button available.
Click on the “Sign in with Google” Button
https://www.c-sharpcorner.com/ebooks/ 17
Picture 16. See the view Google login available.
Picture 18. Now you can see the login information here.
Successfully we get the Goole OAuth token. retrieve the user token and send it to the Node.js
backend via an API request.
Initialization of State:
const [loginData, setLoginData] = useState(
localStorage.getItem("loginData")
? JSON.parse(localStorage.getItem("loginData"))
: null
);
https://www.c-sharpcorner.com/ebooks/ 18
Your state is initialized correctly, checking if loginData exists in localStorage. If it does, it parses
and uses it; otherwise, it sets the state to null.
if (!res.ok) {
throw new Error("Failed to log in with Google");
}
• The function handleLogin takes googleData as an argument, which contains the Google
authentication data.
• It makes a POST request to the server with the googleData token.
• If the response is not OK, it throws an error.
• If the response is successful, it parses the JSON response, updates the state with the
received data, and stores this data in localStorage.
• If an error occurs at any point, it logs the error to the console.
https://www.c-sharpcorner.com/ebooks/ 19
Login.jsx Pages code
https://www.c-sharpcorner.com/ebooks/ 20
5
Node.js backend
application.
overview
https://www.c-sharpcorner.com/ebooks/ 21
In my previous article, I provided a step-by-step guide on Setting up the Node.js Environment
and Running a Simple Node Server Project. If you're new to Node.js, I recommend reading that
article first for detailed instructions. Once you're familiar with the setup, return to this article for
further insights.
To install a npm package, go to the terminal and type npm init -y. This command initializes a
new npm project with default settings, skipping the prompts that npm init would normally display.
During the standard npm init process, you'll be asked several questions, including the package
name. You can specify your own package name, or it will default to the name of the project
folder. By using the -y flag, npm init -y automatically sets the package name to the default
project folder name without prompting you for input.
Picture 19. Now you can see the \package.json info here.
• Express: A web application framework for Node.js that simplifies building and managing
web applications.
• Body-parser: A middleware for Node.js that parses incoming request bodies in a
middleware before your handlers, making it easier to handle form submissions and
JSON payloads.
• Nodemon: A utility that automatically restarts your Node.js application when file changes
in the directory are detected, streamlining development and testing.
• Mongoose: An object data modeling (ODM) library for MongoDB and Node.js, providing
a straightforward, schema-based solution to model your application data.
https://www.c-sharpcorner.com/ebooks/ 22
To install these packages, run the following command in your project directory:
Picture 20. You can see the dependencies here. I installed express, body-parser, nodemon,
and Mongoose npm packages.
Create index.js
Create an Index page index.js.
This line imports the Express module, which is a web framework for Node.js. express will be
used to
https://www.c-sharpcorner.com/ebooks/ 23
Define a route for GET requests to the root URL ("/")
app.get("/", function (req, res) {
res.send("Hello C# Corner.").
});
It has a callback function (req, res) req = it listens to the incoming request object, and res =
responds accordingly using the response object.
It listens for incoming requests on port 3000. Once the server is running, it will be accessible via
http://localhost:3000.
"scripts": {
"start": "nodemon index.js",
},
Picture 21. You can see the this run the node js “npm start”. App listen 5000, script running
nodemon index.js.
https://www.c-sharpcorner.com/ebooks/ 24
Picture 22. You can see this GET method call, which returns the message 'Hello C# Corner.'
with a status of success (200 OK).
https://www.c-sharpcorner.com/ebooks/ 25
6
MongoDB Connection
String
Overview
https://www.c-sharpcorner.com/ebooks/ 26
Get the MongoDB Connection String
Creating a MongoDB Atlas Account and Establishing a MongoDB Connection If you're looking to
create a MongoDB Atlas account and set up a MongoDB connection, I've got you covered. I’ve
detailed these processes in my previous articles, which you can find linked below.
Picture 23. Click on the "Connect" button in the cluster on the dashboard.
DB Connection
https://www.c-sharpcorner.com/ebooks/ 27
Picture 24. Click on the "Drivers" tab in the dashboard.
Picture 25. 01. You will select your driver with the version. 02. You can copy the Connection
string.
https://www.c-sharpcorner.com/ebooks/ 28
7
Connect the API with
MongoDB
Overview
https://www.c-sharpcorner.com/ebooks/ 29
Create the API env file
Now I'm going to create the env file. In this article, I explain the process under the heading '04.5
Create the env file'. Follow these steps:"
MONGO_DB=mongodb+srv://<Username>:<Password>@<clusterName>.mongodb.net/
<your_database_name>?retryWrites=true&w=majority
Now im going to create the DB as a “GoogleOAuth”. Env file mongoDB variable set DB name.
MONGO_DB=mongodb+srv://<Username>:<Password>@<clusterName>.joofg8v.mong
odb.net/<GoogleOAuth>?retryWrites=true&w=majority
Picture 26. You can see the env setup MONGO_DB and PORT.
You can past you mongodb connection string in MONGO_DB in env.
DB Connection Check
Check whether the DB connection is successful or not.
require("dotenv").config();
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const MONGO_DB = process.env.MONGO_DB;
const PORT = process.env.PORT;
https://www.c-sharpcorner.com/ebooks/ 30
This line imports the Mongoose library, which is an Object Data Modeling (ODM) library for
MongoDB and Node.js.
These lines load the MongoDB connection string (MONGO_DB) and the port number (PORT)
from environment variables.
Connect to MongoDB
mongoose
.connect(MONGO_DB)
.then(() => {
console.log("connected to MongoDB");
app.listen(PORT, () => {
console.log(`Node API app is running on port ${PORT}`);
});
})
.catch((error) => {
console.log(error);
});
mongoose.connect(MONGO_DB): This attempts to connect to the MongoDB database using
the connection string stored in the MONGO_DB environment variable. It returns a promise. If the
connection is successful, the callback function inside then is executed.
.catch((error) => { ... }): If the connection fails, the callback function inside catch is executed.
https://www.c-sharpcorner.com/ebooks/ 31
Verify the token using the Google API
• Verify the token using the Google API.
• Extract the user information.
• Check if the user exists in the MongoDB database; if not, create a new user record.
• Generate a session token for the authenticated user.
Picture 28. Verify the token and Check if the user exists in the MongoDB database; if not,
create a new user record.
https://www.c-sharpcorner.com/ebooks/ 32
Here i can share userModel.js
REACT_APP_GOOGLE_CLIENT_ID =
REACT_APP_GOOGLE_API_KEY=
Jsonwebtoken is a library in Node.js used to create, sign, and verify JSON Web Tokens (JWTs).
JWTs are a compact, URL-safe means of representing claims between two parties. They are
often used for authentication and secure information exchange.
npm i jsonwebtoken
CORS is a node.js package for providing a Connect/Express middleware that can be used to
enable CORS with various options.
npm i cors
app.use(express.json());
app.use(cors({ origin: "http://localhost:3000" }));
https://www.c-sharpcorner.com/ebooks/ 33
app.post("/api/google-login", async (req, res) => {
const { token } = req.body;
try {
// Verify the token using Google API
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
const { sub, email, name, picture } = payload;
Middleware Setup:
app.use(express.json());
app.use(cors({ origin: "http://localhost:3000" }));
Configures Express to parse JSON and handle CORS for requests from
https://www.c-sharpcorner.com/ebooks/ 34
Google Login Endpoint:
app.post("/api/google-login", async (req, res) => {
const { token } = req.body;
try {
// 01. Verify the token using Google API
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
const { sub, email, name, picture } = payload;
https://www.c-sharpcorner.com/ebooks/ 35
8
Run the Application.
Overview
https://www.c-sharpcorner.com/ebooks/ 36
Go to the GUI folder, open the terminal in your VS Code, and run this command: npm start. The
same command applies to the API folder as well.
Picture 30. Run this command GUI and API : npm start
https://www.c-sharpcorner.com/ebooks/ 37
Picture 33. See the network tab api call “google-login”. Status 200.
https://www.c-sharpcorner.com/ebooks/ 38
9
View the Database.
Overview
https://www.c-sharpcorner.com/ebooks/ 39
Go to the MongoDB cluster on the dashboard.
• Click on Database Button and
• Click on your cluster.
https://www.c-sharpcorner.com/ebooks/ 40
10
Login Data in GUI
Overview
https://www.c-sharpcorner.com/ebooks/ 41
View the Login Data in GUI.
Successfully made the API call as explained in Picture 33. Check the network tab for the API
call 'google-login' with status 200.
const [user, setUser] = useState({});
useEffect(() => {
if (loginData) {
const decodedUser = jwtDecode(loginData.sessionToken);
setUser(decodedUser);
}
}, [loginData]);
• Runs the code inside the useEffect callback function when loginData changes.
• Inside the useEffect callback:
• Checks if loginData is truthy
• Decodes the sessionToken from loginData using jwtDecode.
• Updates the user state with the decoded user object (decodedUser).
setLoginData(null);
• Sets the state variable loginData to null. This likely indicates that the user is no longer
logged in, as null typically represents absence of a logged-in state.
localStorage.removeItem("loginData");
• Removes the item with key "loginData" from the browser's localStorage. This is likely
used to clear any persisted login data stored locally, ensuring the user isn't automatically
logged back in on subsequent visits.
googleLogout();
• Calls a function googleLogout() that presumably handles logging the user out from a
Google-related service or OAuth session.
import React, { useEffect, useState } from "react";
import { GoogleOAuthProvider, GoogleLogin, googleLogout } from "@react-
oauth/google";
import { jwtDecode } from "jwt-decode";
https://www.c-sharpcorner.com/ebooks/ 42
export default function Login() {
const [loginData, setLoginData] = useState(
localStorage.getItem("loginData")
? JSON.parse(localStorage.getItem("loginData"))
: null
);
const [user, setUser] = useState({});
useEffect(() => {
if (loginData) {
const decodedUser = jwtDecode(loginData.sessionToken);
setUser(decodedUser);
}
}, [loginData]);
if (!res.ok) {
throw new Error("Failed to log in with Google");
}
return (
<div className="App">
{loginData ? (
<>
<div>
<img src={user.picture} alt={user.userName} />
https://www.c-sharpcorner.com/ebooks/ 43
<h3>{user.email}</h3>
<h6>{user.userName}</h6>
</div>
<div>
<button onClick={handleLogout}>Logout</button>
</div>
</>
) : (
<div className="App">
<button type="button">
<GoogleOAuthProvider clientId={CLIENT_ID}>
<GoogleLogin
onSuccess={(credentialResponse) => {
handleLogin(credentialResponse.credential);
}}
onError={() => {}}
/>
</GoogleOAuthProvider>
</button>
</div>
)}
</div>
);
}
https://www.c-sharpcorner.com/ebooks/ 44
Summary
The article explores integrating Google OAuth into a MERN (MongoDB, Express.js, React.js,
Node.js) stack application. It begins with an introduction to the MERN stack's components and
benefits. The implementation of Google OAuth involves several key steps:
Throughout the article, detailed steps are provided for setting up both the frontend and backend
components, ensuring a comprehensive guide to implementing Google OAuth in a MERN stack
application.
https://www.c-sharpcorner.com/ebooks/ 45
OUR MISSION
Free Education is Our Basic Need! Our mission is to empower millions of developers worldwide by
providing the latest unbiased news, advice, and tools for learning, sharing, and career growth. We’re
passionate about nurturing the next young generation and help them not only to become great
programmers, but also exceptional human beings.
ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner
MORE BOOKS