Tham's Tech Box

Tham's Tech Box

Firebase Authentication: Realtime auth state monitoring

Firebase Authentication: Realtime auth state monitoring

Subscribe to my newsletter and never miss my upcoming articles

When you build an application, you might be having a situation that you need to watch the authentication state change event. Imaging you need to update the header component with the authenticated user detail whenever the user sign-in successfully to the application. I am going to explain how this can be achieved using the 'onAuthStateChanged()' function provided by firebase authentication module. Next you will see how this can be implemented with code.

<script>
import { auth } from './services/firebase';
import { onAuthStateChanged } from "firebase/auth";

import AuthService from './services/AuthService';

export default {
  setup() {
    onAuthStateChanged(auth, (user) => {
      console.log('User auth changed');
    });
  }
}
</script>

NOTE: Refer my previous article on how to initialize the auth variable.

If you see inside the onAuthStateChanged function, you will get the Promise with the user variable. This object will have the latest authenticated user information which you can you can use it inside your application based on your business requirements.

 
Share this