MERN Google Auth
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
clientIdproperly
โ Accessing backend on port 5173 โ always use backend URL!โ Add
.envIn 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.tsxcomponent: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โ
.envIn backend root:GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com JWT_SECRET=your_jwt_secret_keyโ
googleAuth.tscontroller: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.tsorindex.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, });
