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:
bashnpm install @react-oauth/google🧠 Mistake to avoid:
❌ Not setting
clientIdproperly
❌ Accessing backend on port 5173 ← always use backend URL!✅ Add
.envIn frontend root:basicVITE_GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com VITE_BACKEND_URL=http://localhost:5000✅
main.tsx(entry point):typescriptimport { GoogleOAuthProvider } from "@react-oauth/google"; const clientId = import.meta.env.VITE_GOOGLE_CLIENT_ID; <GoogleOAuthProvider clientId={clientId}> <App /> </GoogleOAuthProvider>✅
GoogleAuth.tsxcomponent:typescriptimport { 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:
bashnpm install google-auth-library✅
.envIn backend root:bashGOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com JWT_SECRET=your_jwt_secret_key✅
googleAuth.tscontroller:typescriptimport { 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.tsorindex.ts:typescriptimport { googleAuth } from "./controllers/googleAuth"; // adjust path app.post("/api/v1/google-signin", googleAuth);
✅ 4. Mongoose User Schema
typescriptconst userSchema = new mongoose.Schema({ username: String, email: { type: String, required: true, unique: true }, password: String, googleID: String, });