Next.js Firebase Google Auth Redirect Fails to Authenticate User

I’m trying to implement Google authentication in my Next.js application using Firebase. The flow works up to the point where the user selects their Google account. After that, the user is redirected back to the login page, but they are not authenticated. Instead, I see the following console logs indicating that no user is authenticated and no redirect result is found:

No user authenticated
Redirect result: null
No redirect result found
Redirect result: null
No redirect result found

What I Tried:

  • I implemented Firebase Google authentication in my Next.js application.
  • I set up Firebase configuration and initialized authentication in /lib/firebase.js.
  • I created a login page at /app/login/page.js with a Google login button.
  • I configured the redirect result handling to capture the user data after Google sign-in and redirect the user to the dashboard.
  • Verified my firebase project has the correct redirect uri. I may’ve done this wrong however.

What I Expected:

  • After clicking the “Login with Google” button, the user should be redirected to choose a Google account.
  • Upon selecting an account, the user should be redirected back to the application.
  • The user data should be captured, stored, and the user should be redirected to the dashboard.

What Actually Happened:

  • After selecting a Google account, the user is redirected back to the login page.
  • The console logs show that no user is authenticated and no redirect result is found.
  • Console logs:
    No user authenticated
    Redirect result: null
    No redirect result found
    Redirect result: null
    No redirect result found
    

Login Page

"use client";

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { signInWithGoogle, getRedirectResultHandler, auth } from '@/lib/firebase';
import { useToggle } from '@mantine/hooks';
import { useForm } from '@mantine/form';
import { Paper, Group, Title } from '@mantine/core';
import { GoogleButton } from '@/components/buttons/GoogleButton';
import { useUser } from '@/context/UserContext';
import { onAuthStateChanged } from 'firebase/auth';
import classes from './page.module.css';

export default function AuthenticationImage() {
  const router = useRouter();
  const { setUser } = useUser();
  const [type, toggle] = useToggle(['login', 'register']);
  const form = useForm({
    initialValues: {
      email: '',
      name: '',
      password: '',
      terms: true,
    },
    validate: {
      email: (val) => (/^S+@S+$/.test(val) ? null : 'Invalid email'),
      password: (val) => (val.length <= 6 ? 'Password should include at least 6 characters' : null),
    },
  });

  useEffect(() => {
    const handleRedirectResult = async () => {
      console.log('Checking redirect result...');
      const result = await getRedirectResultHandler();
      console.log('Redirect result:', result);

      if (result) {
        const { user } = result;
        const userData = {
          photoURL: user.photoURL,
          displayName: user.displayName,
          email: user.email,
          uid: user.uid,
        };
        console.log('User data retrieved:', userData);
        setUser(userData);

        try {
          const res = await fetch('http://localhost:5000/api/login-google', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(userData),
          });

          if (!res.ok) {
            throw new Error(`HTTP error! status: ${res.status}`);
          }

          const result = await res.json();
          console.log('API response:', result);
          localStorage.setItem('user', JSON.stringify(userData));
          router.push('/dashboard');
        } catch (error) {
          console.error('Error posting user data to API:', error);
        }
      } else {
        console.log('No redirect result found');
      }
    };

    const handleAuthStateChange = (user) => {
      if (user) {
        const userData = {
          photoURL: user.photoURL,
          displayName: user.displayName,
          email: user.email,
          uid: user.uid,
        };
        console.log('User authenticated:', userData);
        setUser(userData);
        router.push('/dashboard');
      } else {
        console.log('No user authenticated');
      }
    };

    handleRedirectResult();
    const unsubscribe = onAuthStateChanged(auth, handleAuthStateChange);

    return () => unsubscribe();
  }, [router, setUser]);

  const handleLogin = async () => {
    try {
      await signInWithGoogle();
    } catch (error) {
      console.error('Login failed', error);
    }
  };

  return (
    <div className={classes.wrapper}>
      <div className={classes.overlay}></div>
      <Paper className={classes.form} radius={0} p={30}>
        <Title order={2} className={classes.title} ta="center" mt="md" mb={50}>
          Welcome to Wealth Wise!
        </Title>
        <Group grow mb="md" mt="md">
          <GoogleButton radius="xl" className={classes.button} onClick={handleLogin}>Login with Google</GoogleButton>
        </Group>
      </Paper>
    </div>
  );
}

New contributor

Jayana N is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật