Back to Blog

MERN Google Auth

✅ 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:

    bash
    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:

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

    main.tsx (entry point):

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

    GoogleAuth.tsx component:

    typescript
    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:

    bash
    npm install google-auth-library

    .env In backend root:

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

    googleAuth.ts controller:

    typescript
    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:

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

    ✅ 4. Mongoose User Schema

    typescript
    const userSchema = new mongoose.Schema({ username: String, email: { type: String, required: true, unique: true }, password: String, googleID: String, });
Based in Greater Noida, IndiaCurrently