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.