Search code examples
firebasegoogle-oauthnext.js13

Firebase Google Auth Login in Nextjs 13


I want to implement Google Oauth login and maintain login status even when the user refreshes the page using Firebase.

signInWithRedirect redirects to the Google login page, but getRedirectResult fails to retrieve user authentication information upon successful login.

What is problem?? and then, teach me how to maintain login status even when the user refreshes the page in nextjs 13 or React.

"use client";

import { useState, useEffect } from "react";
import { getAuth, signInWithPopup, GoogleAuthProvider, signInWithRedirect, getRedirectResult } from "firebase/auth";
import { app } from "../../firebase_config";
import { useAuth } from "./AuthContext";
import { FcGoogle } from "react-icons/fc";
import s from "./Login.module.css";

export default function Login() {
  const auth = getAuth(app);
  const provider = new GoogleAuthProvider();
  const [user, setUser] = useState(null);
  const { isLoggedIn, login, logout } = useAuth();

  const handleGoogleSignIn = async () => {
    signInWithRedirect(auth, provider)
      .then(async (result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const user = result.user;
        console.log(result);
        console.log(credential);
        setUser(user);
        login();
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      })
      .finally(() => {
        getRedirectResult(auth).then((result) => {
          console.log(result);
        });
      });
  };

  return (
    <div>
      {isLoggedIn ? (
        <div className={s.userProfile}>
          <img className={s.userImg} src={user.photoURL}></img>
          <span>{user.displayName}</span>
        </div>
      ) : (
        <button onClick={handleGoogleSignIn}>
          <FcGoogle style={{ fontSize: "em" }} />
          Login
        </button>
      )}
    </div>
  );
}

I confirmed that the pop-up login method works correctly, but I would like to use the redirect method.


Solution

  • signInWithRedirect navigates away from your application, therefore you will need to call getRedirectResult in a separate function inorder to get the response when the page redirects back.

      const { isLoggedIn, login, logout } = useAuth();
    
      useEffect(() => {
        getRedirectResult(auth)
          .then((result) => {})
          .catch((error) => {});
      }, []);
    
      ... rest of your code