Friday, December 5, 2025

thumbnail

OAuth with Google in MERN

 OAuth with Google in MERN (MongoDB, Express, React, Node.js)


Google OAuth allows users to log in to your MERN application using their Google account. Instead of handling passwords, your app relies on Google for authentication, improving security and user experience.


A typical Google OAuth workflow in MERN looks like this:


User clicks “Sign in with Google” on the React frontend


Google’s OAuth page opens


User logs in and approves permissions


Google redirects back to your backend’s callback URL with an authorization code


The Node/Express server exchanges the code for user profile data + tokens


The backend verifies/stores the user in MongoDB


A session or JWT is returned to the React frontend


1. Setup Requirements

Create a Google OAuth Credentials


Go to: Google Cloud Console → APIs & Services → Credentials → Create OAuth Client ID


You will need to set:


Authorized JavaScript Origins


Example: http://localhost:3000


Authorized Redirect URIs


Your backend callback


Example: http://localhost:5000/auth/google/callback


Google will give you:


CLIENT_ID


CLIENT_SECRET


Save these for your backend.


2. Backend Setup (Node.js + Express)


You can use:


passport.js with passport-google-oauth20 (most common)

or


google-auth-library + manual token verification


Below is the Passport.js version (easier to start).


Install packages

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


Configure Passport Strategy

// passport.js

const GoogleStrategy = require("passport-google-oauth20").Strategy;

const passport = require("passport");

const User = require("./models/User");


passport.use(

  new GoogleStrategy(

    {

      clientID: process.env.GOOGLE_CLIENT_ID,

      clientSecret: process.env.GOOGLE_CLIENT_SECRET,

      callbackURL: "/auth/google/callback",

    },

    async (accessToken, refreshToken, profile, done) => {

      try {

        // Find user in DB

        let user = await User.findOne({ googleId: profile.id });


        if (!user) {

          user = await User.create({

            googleId: profile.id,

            name: profile.displayName,

            email: profile.emails[0].value,

            avatar: profile.photos[0].value,

          });

        }


        return done(null, user);

      } catch (err) {

        return done(err, null);

      }

    }

  )

);


passport.serializeUser((user, done) => {

  done(null, user.id);

});

passport.deserializeUser((id, done) => {

  User.findById(id).then((user) => done(null, user));

});


Express Auth Routes

const express = require("express");

const passport = require("passport");

require("./passport"); // Load passport config


const router = express.Router();


// Step 1: Login redirect to Google

router.get("/google",

  passport.authenticate("google", { scope: ["profile", "email"] })

);


// Step 2: Google callback

router.get("/google/callback",

  passport.authenticate("google", {

    failureRedirect: "/login",

    successRedirect: "http://localhost:3000/dashboard"

  })

);


module.exports = router;


Main Server File

const express = require("express");

const session = require("express-session");

const passport = require("passport");

const authRoutes = require("./routes/auth");


const app = express();


app.use(

  session({

    secret: "SECRET_KEY",

    resave: false,

    saveUninitialized: true,

  })

);


app.use(passport.initialize());

app.use(passport.session());


app.use("/auth", authRoutes);


app.listen(5000, () => console.log("Server running on port 5000"));


3. MongoDB User Schema Example

const mongoose = require("mongoose");


const UserSchema = new mongoose.Schema({

  googleId: { type: String, required: true },

  name: String,

  email: String,

  avatar: String,

});


module.exports = mongoose.model("User", UserSchema);


4. Frontend (React)


On the frontend, the easiest method is to redirect the user to your backend:


React Login Button

const Login = () => {

  const googleLogin = () => {

    window.location.href = "http://localhost:5000/auth/google";

  };


  return (

    <button onClick={googleLogin}>

      Sign in with Google

    </button>

  );

};


export default Login;



The server handles the whole OAuth flow, then redirects back to your React page (e.g., /dashboard).


5. Optional: Using JWT Instead of Sessions


Instead of sessions, many MERN developers prefer JWT auth.


Workflow:


Google callback receives profile


Backend generates a JWT


React stores the JWT in a secure cookie or memory


User stays logged in


Let me know if you want a full Google OAuth + JWT MERN example.


6. Summary


Google OAuth in MERN involves:


React: sends user to /auth/google


Express + Passport: manages OAuth, retrieves Google profile


MongoDB: stores or updates the user record


Redirect: sends user back to React after login


Auth session/JWT: keeps the user logged in

Learn MERN Stack Training in Hyderabad

Read More

Avoiding Injection Attacks in MongoDB

HTTPS in MERN Applications

Secure File Uploads in MERN

Rate Limiting & Throttling with Express

Visit Our Quality Thought Training Institute in Hyderabad

Get Directions 

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive