How to create Authentication Guard Component

How to create Authentication Guard Component

Setup Firebase Authentication: Ensure you have set up Firebase Authentication properly. This includes setting up a Firebase project, enabling the Authentication service, and configuring sign-in methods (like email/password, Google, etc.). Create Firebase Configuration File: Ensure you have a Firebase configuration file (usually named firebase.html or similar) where you initialize Firebase with your configuration.

Create an AuthGuard.js file. This component will handle the authentication logic.

Inside the AuthGuard component:

  • Import necessary modules from React and useNavigate from react-router-dom.
  • Import the 'auth' object from './firebase' file.
  • Define a functional component AuthGuard that takes 'children' as a prop.
  • Initialize navigate function using the useNavigate hook from react-router-dom.
  • Initialize 'isLoggedIn' state variable with false using useState hook.

Implement the useEffect hook:

  • Call onAuthStateChanged method on 'auth' object to listen for authentication state changes.
  • Update the 'isLoggedIn' state based on whether the user (from onAuthStateChanged) is null or not.
  • If 'isLoggedIn' is false, redirect the user to the login page using navigate('/login').

Ensure useEffect has the correct dependencies (auth, navigate) specified.

In your return statement:

  • If isLoggedIn is true, render the children (components wrapped inside AuthGuard).
  • If isLoggedIn is false, return null to prevent rendering unauthorized content.