I’m trying to protect routes in my React app. The Home
page is being protected, but I also want to stop the user to go back to the login page if the isLoggedIn
is true, and if it is false then he can’t access the home and will be redirected to the Login
page.
This is the PrivateRoutes
that I have written to protect the routes which is protecting the home but the user can still access the Login
page, how can I stop this?
PrivateRoutes.jsx:
import { Outlet, Navigate } from "react-router-dom";
const PrivateRoutes = () => {
const isLoggedIn = true;
return isLoggedIn ? <Outlet /> : <Navigate to="/login" />;
};
export default PrivateRoutes;
This is the App.jsx:
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Login from "./pages/Login";
import SignUp from "./pages/SignUp";
import Home from "./pages/Home";
import PrivateRoutes from "./utils/PrivateRoutes";
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route element={<PrivateRoutes />}>
<Route index element={<Home />} path="/" exact />
</Route>
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
</>
);
}
export default App;
2
Answers
import { Outlet, Navigate, useNavigate } from "react-router-dom";
If you would like to prevent authenticated access to the
"/login"
route then you can also protect that route under a similar condition as the private routes. Create another layout route component that applies the inverse condition of thePrivateRoute
component, e.g. it redirects users that are authenticated.Example: