You can create a different set of routes based on a condition(e.g: user logged in or not) and then have a default redirect route for each condition. For creating this set, you'll have to know what routes are accessible under what states, for instance, an unauthorized user cannot navigate to routes that include any create, delete, or update actions, if a user tries to access such routes they should be redirected to a default route like a login page. Similarly, an authorized user should not be able to access login/signup routes. You can structure your code like below, this is with regards to auth state, but you are free to use any other conditions as well:
In your main component(typically App.js
/App.tsx
where you define your routes)
let routes;
if(loggedIn){
routes = (
<Routes>
<Route path='/' element={<HomePage/>}/>
<Route path='/groups' element={<Groups/>}/>
<Route path='/some/other/route/:id' element={<AuthCompN/>}/>
<Route path='*' element={<Navigate to ='/'/>}/>
</Routes>
)
}
else{
routes = (
<Routes>
<Route path='/auth' element={<Login/>}/>
<Route path='*' element={<Navigate to="/auth"/>}/>
</Routes>
)
}
return (
<BrowserRouter>
<div className="fixed w-full h-full">
{isLoggedIn&&<Navbar />}
{routes}
</div>
</BrowserRouter>
);
As we can see, the variable routes
is assigned different set of routes based on the login state. The last route whose path is marked *
is any other path other than the ones defined above it, so if a user is logged in and tries to access or go back to /login
path, they are redirected to the route that renders home component or something similar. Same logic applies when a user is not logged in and tries to access protected routes.