1

My problem is that the moment i navigate to the homepage and the user is not authenticated the page shows for a split second and then move on to the login page. I want it to redirect to login only and not show the homepage for a split second

I already created a private route in my project but for a split second the protected routes shows when i navigate on to it.

here is my code:

AuthContextProvider

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);
    });

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

  const value = { user };
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

PrivateRoute.js

const PrivateRoute = ({ children }) => {
  let { user } = useAuth();

  if (user) {
    return <Outlet />;
  } else {
    return <Navigate to="/login" />;
  }
};

App.js

function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route path="/" element={<Layout />}>
        <Route element={<PrivateRoute />}>
          <Route path="/" element={<Home />} />
          <Route path="/home" element={<Home />} />
          <Route path="/reminders" element={<Reminders />} />
          <Route path="/archive" element={<Archive />} />
          <Route path="/trash" element={<Trash />} />
        </Route>
      </Route>
    </Routes>
  );
}

Loginpage.js

const LoginPage = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const signIn = async () => {
    const provider = new GoogleAuthProvider();
    await signInWithRedirect(auth, provider);
  };

  useEffect(() => {
    onAuthStateChanged(auth, (currentUser) => {
      if (currentUser) {
        navigate("/");
      }
    });
  }, []);

  return (
    <>
      <button
        onClick={signIn}
        className="bg-blue-500 p-3 text-white hover:bg-blue-600"
      >
        Sign In With Google
      </button>
    </>
  );
};
Paul Osorio
  • 43
  • 1
  • 5

1 Answers1

4

Code for hindering the Loggedin User to go to the Login Route

I have created a SpecialRoute which will redirect the loggedIn User to the mainpage if the user tries to go the login page.

SpecialRoute.js

import { Login } from '../pages/Login';
import { useAuth } from '../firebase-config';
import React from 'react';
import { Outlet, Navigate } from 'react-router-dom';
// import { useAuth } from '../firebase-config';

export const SpecialRoute = () => {
  const user = useAuth();
  return user ? <Outlet /> : <Navigate to="/" replace />;
};

App.js

 <Route element={<SpecialRoute />}>
    <Route path="/login" element={<Login />} />
  </Route>

In your Private Route Component, do this :-

const PrivateRoute = ({ children }) => {
  let { user } = useAuth();

return typeof user === 'undefined' ? (
    <h1>Loading.....</h1>
  ) : user ? (
    <Outlet />
  ) : (
    <Navigate to="/login" />
  );
};

Below is how I created my private routes (in Firebase v9):-

useAuth Hook

// custom hook
export function useAuth() {
  //
  const [currentUser, setCurrentUser] = useState<any>();
  useEffect(() => {
    const unSubscribe = onAuthStateChanged(auth, (user) =>
      setCurrentUser(user)
    );
    return unSubscribe;
  }, []);
  return currentUser;
}

My PrivateRoute/ProtectedRouted Component

import { Login } from '../pages/Login';
import React from 'react';
import { Outlet } from 'react-router-dom';
import { useAuth } from '../firebase-config';

export const ProtectedRoute = () => {
  const user = useAuth();

  console.log('/////user autheticated', user);

  return typeof user === 'undefined' ? (
    <h1>Loading.....</h1>
  ) : user ? (
    <Outlet />
  ) : (
    <Login />
  );
};

App.js

function App() {
  return (
    <>
      <Router>
        <Routes>
          <Route element={<ProtectedRoute />}>
            <Route path="/" element={<Home />} />
          </Route>
          <Route path="/login" element={<Login />} />
          <Route path="/signup" element={<Signin />} />
        </Routes>
      </Router>
    </>
  );
}

Abdullah Ch
  • 1,678
  • 1
  • 13
  • 31