DEV Community

Cover image for Google Login OAuth Error:401 in React Frontend
Dhivya M
Dhivya M

Posted on

Google Login OAuth Error:401 in React Frontend

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cflrqbnar8aef26t7lv3.png)Login.jsx
import{ useState } from "react";
import { GoogleOAuthProvider, GoogleLogin } from "@react-oauth/google";
import { FaFacebook, FaLinkedin } from "react-icons/fa";
import { Link, useNavigate } from "react-router-dom";
import { facebookLogin, linkedinLogin } from "../../utils/api";
import logo from "../../assets/logo.png"; // Ensure the correct path to your logo

const clientId = "xxxx"; // Replace with your actual Google client ID

const Login = () => {
  const [error, setError] = useState("");
  const navigate = useNavigate();

  const handleGoogleSuccess = async (credentialResponse) => {
    try {
      const token = credentialResponse.credential;

      // Fetch user profile info from Google
      //const userInfoResponse = await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${token}`, {
      const userInfoResponse = await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?token=${token}`);
      if (!userInfoResponse.ok) {
        throw new Error(`Failed to fetch user info: ${userInfoResponse.statusText}`);
      }
      const userInfo = await userInfoResponse.json();
      console.log("User info:", userInfo);

      // Send user info to the backend
      const response = await fetch("http://localhost:3000/auth/gxxxxx", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          firstName: userInfo.given_name || "",
          lastName: userInfo.family_name || "",
          email: userInfo.email || "",
        }),
      });

      if (!response.ok) {
        throw new Error(`Backend responded with status: ${response.status}`);
      }

      const data = await response.json();
      console.log("Backend response:", data);

      if (data.token) {
        localStorage.setItem("token", data.token);
        navigate("/");
      } else {
        setError(data.message || "Google login failed");
      }
    } catch (err) {
      setError(err.message || "An error occurred during Google login");
    }
  };

  const handleGoogleFailure = () => {
    setError("Google login failed. Please try again.");
  };

  return (
<GoogleOAuthProvider clientId={clientId}>
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
<div className="w-full max-w-md p-8 bg-white rounded shadow">
<img src={logo} alt="Logo" className="w-24 mx-auto mb-6" />
<h2 className="mb-4 text-2xl text-center">Login</h2>
<div className="mb-4">
<GoogleLogin
              onSuccess={handleGoogleSuccess}
              onError={handleGoogleFailure}
            />
</div>
          {error && <p className="mb-4 text-sm text-red-500">{error}</p>}
<div className="mt-6">
<button
              onClick={facebookLogin}
              className="flex items-center justify-center w-full p-2 mb-2 text-white bg-blue-700 rounded hover:bg-blue-800"
>
<FaFacebook className="mr-2" /> Sign in with Facebook
</button>
<button
              onClick={linkedinLogin}
              className="flex items-center justify-center w-full p-2 text-white bg-blue-600 rounded hover:bg-blue-700"
>
<FaLinkedin className="mr-2" /> Sign in with LinkedIn
</button>
</div>
<div className="mt-4 text-center">
<a
              href="/forgot-password"
              className="text-blue-500 hover:underline"
>
              Forgot Password?
</a>
</div>
<div className="mt-4 text-center">
<span>Dont have an account? </span>
<Link to="/register" className="text-blue-500 hover:underline">
              Create one
</Link>
</div>
</div>
</div>
</GoogleOAuthProvider>
  );
};

export default Login;


Enter fullscreen mode Exit fullscreen mode

Hello Team,
Front End: React.js. Google OAuth Login
Backend: Express API Endpoint
Any Suggestion or feedback welcome. Thanks in advance.

Top comments (0)