Google OAuth implementation in MERN stack

·         Get Your Client Id

o   Go to : http://www.console.cloud.google.com

o   Select or creat a new project and Go to Branding>Clients and create a new Client

o   Add http://localhost and http://localhost:port both in the Authorised JavaScript origins sections

Front end:

  • Install : @react-oauth/google

import { GoogleLogin, GoogleOAuthProvider } from "@react-oauth/google"
export default function App() {
  const handleSuccess = async (response) => {
    try {
      const token = response.credential
      let serverResponse = await fetch("http://localhost:8080/api/auth/google",
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({token})
        })
      if(!serverResponse.ok) throw new Error("Could not login!")
      serverResponse = await serverResponse.json()
      console.log(serverResponse)
    } catch (error) {
      console.log(error.message)
    }
  }

  const handleError = () => {
    console.log("Could not sign in!")
  }

  return (
    <div style={{ width: "200px" }}>
      <GoogleOAuthProvider clientId={import.meta.env.VITE_GOOGLE_CLIENT_ID}>
        <GoogleLogin
          onSuccess={handleSuccess}
          onError={handleError}
        />
      </GoogleOAuthProvider>
    </div>
  )
}


Backend:

const express = require("express")
const app = express()
const cors =require("cors")
app.use(cors())

app.post("/api/auth/google", express.json(), async (req, res) => {
    try {
       
        const { token } = req.body
        let response = await fetch(
        "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + token
        )
        if (!response.ok) throw new Error("Could not verify google token!")
        response = await response.json()
        console.log("response", response)
        res.status(200).json({ response })
    } catch (error) {
        res.status(400).json({ error: "Failed to verify token!" })
    }
})

app.listen(8080, () => console.log("Listening on port 8080"))

Comments

Popular posts from this blog

Razorpay Payment Integration (MERN STACK)

How to add reCAPTCHA validation to your MERN stack app