Next.js Discord

Discord Forum

Implementing a /logout page with firebase

Answered
Egyptian Mau posted this in #help-forum
Open in Discord
Egyptian MauOP
So I'm building a basic app with register, login and logout functionality using firebase.
The register and login works fine, but how do I implement a logout page?
My current approach is:
/src/app/logout/page.tsx

'use client';

import React from 'react';
import { useRouter } from 'next/navigation';
import { onAuthStateChanged, signOut } from 'firebase/auth';
import { useAuth } from '@/components/firebase-client/auth';


export default function LogoutPage() {
  const router = useRouter();
  const firebaseAuth = useAuth();

  React.useEffect(() => {
    onAuthStateChanged(firebaseAuth, user => {
      if (user) {
        signOut(firebaseAuth);
      }
      router.push('/');
    });
  }, [ firebaseAuth, router ]);

  return (
    <></>
  );
}

The issue here is, suppose I login with a user, and then logs out by calling /logout, it just logs out fine. But if I register a new user right after logging out one, the registration also signs in the newly registered user. The callback inside onAuthStateChanged gets called without even visiting /logout.
As far as I understand, it is being called since logging in after registration changes the auth state and hence calling the authStateChange method and is being cached since I visited it previously.
Answered by Egyptian Mau
Edit: Fixed.
In the code above, I just had to pass an empty dependencyArray in useEffect so it executes only when it is mounted. In the above code, it gets executed every time any of the dependency changes (in this case, firebaseAuth changes as it gets populated with currentUser data on logging in)
View full answer

1 Reply

Egyptian MauOP
Edit: Fixed.
In the code above, I just had to pass an empty dependencyArray in useEffect so it executes only when it is mounted. In the above code, it gets executed every time any of the dependency changes (in this case, firebaseAuth changes as it gets populated with currentUser data on logging in)
Answer