Can I use this scenario to handle protected routes in React?
I use session-storage to save login data like token etc.
Is it best practice to use this scenario for redirecting un-authorized users?
useEffect(() => {
if (token === null) {
navigate('/users/login');
}
}, []);
because I've 2 kind of pages in app.
some pages should load with token and some not
I would rather implement a component that does this check for you, as suggested here, so you don't have to check for the token in every component:
// In case authentication is required, wrap the component to be rendered inside PrivateRoute
<Route
path="/protectedPage"
element={
<PrivateRoute>
<ProtectedPage/>
</PrivateRoute>
}
/>
// In case no authentication is required, just render the element as it is
<Route
path="/unprotectedPage"
element={
<UnprotectedPage/>
}
/>
// In case you don't want to show the page to an authenticated user
<Route
path="/protectedPage"
element={
<PrivateRoute redirectIfAlreadyAuthenticated={true}>
<Login/>
</PrivateRoute>
}
/>
function PrivateRoute({ children, redirectIfAlreadyAuthenticated=false }) {
if(redirectIfAlreadyAuthenticated)
return token? <Navigate to="/" /> : children;
else
return token? children : <Navigate to="/users/login" />;
}