Implementing Route Guards in TanStack Router
Provide an example of implementing route guards with TanStack Router to protect certain routes and redirect users based on authentication status.
import { Outlet, Navigate } from 'react-router-dom';
Imports Outlet (to render child components) and Navigate (for redirection) from TanStack Router (formerly react-router-dom).
const useAuth = () => { /* Custom hook to check auth status */ };
Defines a custom hook (useAuth) that checks the user's authentication status. Replace the contents with your auth logic.
const ProtectedRoute = ({ children }) => {
const isLoggedIn = useAuth();
return isLoggedIn ? children : <Navigate to='/login' replace />;
};
ProtectedRoute component that uses the useAuth hook to check if the user is logged in. If not, it redirects to the login page.
const App = () => (
<Routes>
<Route path='/' element={<ProtectedRoute><HomePage /></ProtectedRoute>} />
/* Define more routes here */
</Routes>
);
Example of using ProtectedRoute in your application's route configuration to protect the HomePage route.