How to Implement Google Sign In using Firebase in React JS MERN

How to implement Google Sign In using Firebase in React JS MERN

Here are steps –

1. Create a component  –  “OAuth.jsx”

2. Add this component in Sign In and Sign Up page where you want to add this functionality.

3. Design “OAuth.jsx” Page –

import { Button } from ‘flowbite-react’
import React from ‘react’
import {AiFillGoogleCircle} from ‘react-icons/ai’
import { GoogleAuthProvider, getAuth, signInWithPopup } from ‘firebase/auth’
import { app } from ‘../firebase’
import {useDispatch} from ‘react-redux’
import {signInSuccess} from ‘../redux/user/userSlice.js’
import {useNavigate} from ‘react-router-dom’

 

const OAuth = () => {
    const auth=getAuth(app)
    const dispatch=useDispatch();
    const navigate=useNavigate();
    const handleGoogleClick=async()=>{
        const provider=new GoogleAuthProvider()
        provider.setCustomParameters({prompt:‘select_account’})
        try {
            const resultsFromGoogle=await signInWithPopup(auth, provider)
            const res=await fetch(‘/api/auth/google’, {
                method:‘POST’,
                headers:{‘Content-Type’:‘application/json’},
                body:JSON.stringify({
                    name:resultsFromGoogle.user.displayName,
                    email:resultsFromGoogle.user.email,
                    googlePhotoUrl:resultsFromGoogle.user.photoURL
                }),

 

            })
            const data=await res.json();
            if(res.ok){
                dispatch(signInSuccess(data))
                navigate(‘/’)
            }
            console.log(resultsFromGoogle)
        } catch (error) {
            console.log(error)
        }
    }
  return (
    <div className=‘mt-2 w-full’>
        <Button type=‘button’ gradientDuoTone=‘pinkToOrange’ className=‘w-full’ onClick={handleGoogleClick}> <AiFillGoogleCircle className=‘w-6 h-8 mr-2’/> Continue With Google</Button>
    </div>
  )
}

 

export default OAuth
 

4. Open firebase > go to console > Add Project > Blog Name > Create project > web > App name > register app >

npm i firebase

5. Create a file “firebase.js” inside “src” folder

copy firebase code and paste it in firebase.js –

// Import the functions you need from the SDKs you need
import { initializeApp } from “firebase/app”;
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app’s Firebase configuration
const firebaseConfig = {
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: “reactblog-89556.firebaseapp.com”,
  projectId: “reactblog-89556”,
  storageBucket: “reactblog-89556.appspot.com”,
  messagingSenderId: “195064726794”,
  appId: “1:195064726794:web:2b126914e45b5b2423e6f3”
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);

6. Create a .env file inside client folder. We have another .env in the root.

VITE_FIREBASE_API_KEY=“AIzaSyCjeIp-_0AykGymDszAWySjoM4mmsG17D”
 
7. Firebase > continue to console > Authentication > Get Started > Google > Enable > project name > Gmail account > Save
 

8. Add a route in auth.route.js –

router.post(‘/google’, google)
9. Create a auth.controller.js –
//Google SignIn Controller
export const google=async(req, res, next)=>{
    const {email, name, googlePhotoUrl}=req.body;
    try {
        const user=await User.findOne({email});
        if(user){
            const token=jwt.sign({id:user._id}, process.env.JWT_SECRET_KEY);
            const {password, …rest}=user._doc;
            res.status(200).cookie(‘access_token’, token,{
                httpOnly:true,
            }).json(rest);
        }
        else{
            const generatedPassword=Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-8);
            const hashedPassword=bcryptjs.hashSync(generatedPassword, 10);
            const newUser=new User({
                username:name.toLowerCase().split(‘ ‘).join()+Math.random().toString(9).slice(-4),
                email,
                password:hashedPassword,
                profilePicture:googlePhotoUrl
            });
            await newUser.save();
            const token=jwt.sign({id:newUser._id}, process.env.JWT_SECRET_KEY);
            const {password, …rest}=newUser._doc;
            res.status(200).cookie(‘access_token’, token,{
                httpOnly:true
            }).json(rest);
        }
    } catch (error) {
        next(error)
    }
}
Video Tutorial: