Skip to content

How to Set Up Google OAuth 2.0 Using Passport.js in MERN?

Welcome to this comprehensive tutorial, where we’ll embark on an exciting journey of integrating Gmail authentication seamlessly into your MERN application. Picture this: users effortlessly log into your app through their Gmail accounts. How? Well, the ingenious Gmail OAuth2 protocol comes to the rescue, paving the way for securing user verification and granting them confidence entry to your application. So, gear up as we take a deep dive into an illuminating, step-by-step guide on weaving the magic of Gmail authentication into the fabric of your backend.

Backend Setup (Node.js & Express):

Step 1

We have some dependencies before jumping into implementation so for dependencies we need Google Credentials which include Client ID and Client Secret which we can get from the Google developer console how can we get these credentials?  The steps are given below:

 
Go to Google API console > Create a new project > On the left side bar click on credentials > Click on the “Create Credentials” button and choose “OAuth client ID” > Select “Web application” as the application type > Enter a name for your OAuth client ID > In the “Authorized JavaScript origins” field, enter the URL of your application’s server (e.g., “http://localhost:8080″ if you are running it locally) > In the “Authorized redirect URIs” field, enter the callback URL for the authentication flow (e.g., “http://localhost:8080/auth/google/callback“) > Click the “Create” button to create your OAuth client ID > You will now see your newly created OAuth client ID. Note down the “Client ID” and “Client Secret” values as these will be used in your application.

Step 2

Now we have our credentials from the Google developer console and we set our server URL and a Callback URL let’s create our project open the terminal and create a new folder for our project here are the commands:

mkdir backend
cd backend

Step 3

Initialize a Node.js project and install the required packages:

npm init
npm install express passport passport-google-oauth20 mongoose express-session

Step 4

Create a new file named ‘server.js’ inside the ‘backend’ directory and there we will

  • The MongoDB connection URL should be replaced with your own MongoDB URL.
  • Configure the Google OAuth 2.0 strategy using the client ID, client secret, and callback URL.
  • Use Passport sessions to manage user sessions and authentication.
  • Initiate the Google OAuth flow when users click on the “Login with Google” link. The route should be /auth/google
  • Handle the callback from Google after successful authentication on the route /auth/google/callback
  • log the user out and redirect them to the home page one /logout route
  • Start the server on a specified port which is 8080.
// backend/server.js
   const express = require('express');
   const passport = require('passport');
   const GoogleStrategy = require('passport-google-oauth20').Strategy;
   const session = require('express-session');
   const mongoose = require('mongoose');
   // Initialize Express app
   const app = express();
   // Connect to MongoDB (replace with your MongoDB connection URL)
   mongoose.connect('MongoDB connection URL', {
       useNewUrlParser: true,
       useUnifiedTopology: true
   });
   // Configure Passport with Google OAuth 2.0 strategy
   passport.use(new GoogleStrategy({
       clientID: 'your_client_id', // Replace with your Google OAuth client ID
       clientSecret: 'your_client_secret', // Replace with your Google OAuth client secret
       callbackURL: '/auth/google/callback'
   },
       (accessToken, refreshToken, profile, done) => {
           // Handle user authentication or creation here
           // For this example, we'll log the profile to the console
           console.log(profile);
           done(null, profile);
       }));
   // Set up session and Passport
   app.use(session({
       secret: 'your_secret_key',  // Replace with a strong secret key
       resave: true,
       saveUninitialized: true
   }));
   app.use(passport.initialize());
   app.use(passport.session());
   // Define routes
   app.get('/auth/google',
       passport.authenticate('google', { scope: ['profile', 'email'] })
   );
   app.get('/auth/google/callback',
       passport.authenticate('google', { failureRedirect: '/' }),
       (req, res) => {
           // Redirect after successful authentication
           res.redirect('/dashboard');
       }
   );
   app.get('/logout', (req, res) => {
       req.logout();
       res.redirect('/');
   });
   // Start the server
   const PORT = process.env.PORT || 8080;
   app.listen(PORT, () => {
       console.log(`Server running on port ${PORT}`);
   });

Now let’s move on to integrating the frontend:

Frontend Integration (React):

Step 1

Create a new directory for your frontend, navigate into it, and set up a basic React app:

cd ..
npx create-react-app frontend
cd frontend

Step 2

Edit the ‘src/App.js’ file to display a welcome message and a link to initiate the Google OAuth flow.

   // frontend/src/App.js
   import React from 'react';
   import './App.css';
   function App() {
       return (
           <div className="App">
               <h1>Welcome to My App</h1>
               <a href="/auth/google">Login with Google</a>
           </div>
       );
   }
   export default App;

Running the Application:

Step 1

Add your Google OAuth client ID and client secret to the server.js file.

Step 2

Start the backend server

node backend/server.js

Step 3

In another terminal, navigate to the frontend directory and start the React app:

npm start

Now, when you visit the React app in your browser, you’ll see the “Login with Google” link. Clicking this link will initiate the Google OAuth 2.0 authentication process.

LinkedIn
Twitter
Facebook

More like this:

Custom Handle Drag-and-Drop in React: A Guide to Minimising Rendering

Custom Handle Drag-and-Drop in React: A Guide to Minimising Rendering

Drag and Drop Feature in any application can provide a rich user experience. There are a number of…
Empowering Microservice Architecture with Ambassador and Kafka

Empowering Microservice Architecture with Ambassador and Kafka

In recent years, microservice architecture has emerged as a popular approach for building scalable, flexible, and resilient software…
How to Debug NodeJS App Running Inside Docker Container?

How to Debug NodeJS App Running Inside Docker Container?

The goal of this example is to debug a Node.js application/server running inside a docker container. The guide…

Subscribe to our newsletter for more.

We send our newsletter every two weeks, and write about technology
and building magnetic SaaS products.