Skip to main content

Command Palette

Search for a command to run...

MERN Google Auth

Updated
โ€ข2 min read
A

Hi there! I'm Aditya, a passionate Full-Stack Developer driven by a love for turning concepts into captivating digital experiences. With a blend of creativity and technical expertise, I specialize in crafting user-friendly websites and applications that leave a lasting impression. Let's connect and bring your digital vision to life!

โœ… 1. Google Cloud Setup

Create OAuth 2.0 Credentials:

  • Go to: Google Cloud Console โ€“ Credentials

  • Click Create Credentials โ†’ OAuth Client ID

  • Application type: Web application

    โœ… 2. Frontend Setup (@react-oauth/google)

    ๐Ÿ“ฆ Install:

      npm install @react-oauth/google
    

    ๐Ÿง  Mistake to avoid:

    โŒ Not setting clientId properly
    โŒ Accessing backend on port 5173 โ† always use backend URL!

    โœ… Add .env In frontend root:

      VITE_GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
      VITE_BACKEND_URL=http://localhost:5000
    

    โœ… main.tsx (entry point):

      import { GoogleOAuthProvider } from "@react-oauth/google";
      const clientId = import.meta.env.VITE_GOOGLE_CLIENT_ID;
    
      <GoogleOAuthProvider clientId={clientId}>
        <App />
      </GoogleOAuthProvider>
    

    โœ… GoogleAuth.tsx component:

      import { GoogleLogin } from "@react-oauth/google";
      import axios from "axios";
    
      const GoogleAuth = () => {
        const handleSuccess = async (credentialResponse) => {
          try {
            const res = await axios.post(`${import.meta.env.VITE_BACKEND_URL}/api/v1/google-signin`, {
              credential: credentialResponse.credential,
            });
            localStorage.setItem("token", res.data.token);
            alert("Login successful");
          } catch (err) {
            console.error("Login error:", err);
            alert("Login failed");
          }
        };
    
        return <GoogleLogin onSuccess={handleSuccess} onError={() => alert("Google Login Failed")} />;
      };
    
      export default GoogleAuth;
    

    โœ… 3. Backend Setup

    ๐Ÿ“ฆ Install:

      npm install google-auth-library
    

    โœ… .env In backend root:

      GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
      JWT_SECRET=your_jwt_secret_key
    

    โœ… googleAuth.ts controller:

      import { OAuth2Client } from "google-auth-library";
      import User from "../models/user"; // adjust path
      import jwt from "jsonwebtoken";
    
      const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
    
      export const googleAuth = async (req, res) => {
        try {
          const { credential } = req.body;
          const ticket = await client.verifyIdToken({
            idToken: credential,
            audience: process.env.GOOGLE_CLIENT_ID,
          });
    
          const payload = ticket.getPayload();
          const { email, name, sub: googleID } = payload;
    
          let user = await User.findOne({ email });
          if (!user) {
            user = await User.create({ email, username: name, googleID });
          }
    
          const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
            expiresIn: "7d",
          });
    
          res.status(200).json({ token, user });
        } catch (error) {
          console.error(error);
          res.status(401).json({ message: "Google sign-in failed" });
        }
      };
    

    โœ… Add the endpoint in your backend main.ts or index.ts:

      import { googleAuth } from "./controllers/googleAuth"; // adjust path
    
      app.post("/api/v1/google-signin", googleAuth);
    

    โœ… 4. Mongoose User Schema

      const userSchema = new mongoose.Schema({
        username: String,
        email: { type: String, required: true, unique: true },
        password: String,
        googleID: String,
      });
    

More from this blog

A

Aditya Kumar Gupta

23 posts

Hi there! I'm Aditya, a passionate Full-Stack Developer driven by a love for turning concepts into captivating digital experiences. With a blend of creativity and technical expertise