I have two types of routes Public and Private.
All private routes are accessible only if user is logged in:
return tokenService.token
? (
<>
<Header />
<Suspense fallback={<Spinner className="spinner" />}>
<Outlet />
</Suspense>
<Footer />
</>
) : (
<Navigate to={'/login'} replace />
);
Then we have public routes. Which can be accessible anywhere but /login and /registration routes even they are public if user is logged in they should be redirected to /dashboard in all other cases we show public route.
This is our file for public route
return (
<>
<AuthHeader />
<Suspense fallback={<Spinner className="spinner" />}>
<Outlet />
</Suspense>
<Footer />
</>
)
Main routes file
<Routes>
<Route element={<PublicRoute />}>
<Route path={'/login'} element={<Login />} />
<Route
path={'/registration'}
element={<Registration />}
/>
<Route path={'/terms'} element={<Terms />} />
<Route path={'/privacy'} element={<Privacy />} />
</Route>
<Route element={<AuthRoute />}>
<Route path={'/dashboard'} element={<MyProfile />} />
</Route>
<Route path={'/notfound'} element={<PageNotFound />} />
</Routes>
So what would be the most efficient way to redirect "/login" and "/registration" routes to "/dashboard" route if user is logged in and in all other cases show public routes?
So user should be able to access "/terms" from anywhere but if he is logged in then he doesn't have access to "/login" and "/registration" routes (redirect to "/dashboard").
In current code even user is logged in he can access to all public routes.
Create an anonymous route protector for the log-in and dashboard routes that does the inverse of the private route protector.
Example:
const AnonymousRoute = () => {
return tokenService.token
? <Navigate to="/dashboard" replace />
: <Outlet />;
};
<Routes>
<Route element={<PublicRoute />}>
<Route element={<AnonymousRoute />}>
<Route path="/login" element={<Login />} />
<Route
path="/registration"
element={<Registration />}
/>
</Route>
<Route path="/terms" element={<Terms />} />
<Route path="/privacy" element={<Privacy />} />
</Route>
<Route element={<AuthRoute />}>
<Route path="/dashboard" element={<MyProfile />} />
</Route>
<Route path="/notfound" element={<PageNotFound />} />
</Routes>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With