Enforcing Route Guards for Authenticated Masked Routes
Explain how to implement route guards in TanStack Router to manage access control. This example will cover setting up guards for routes that should be masked and accessible only to authenticated users, redirecting unauthorized users to a login route.
import { createBrowserRouter, RouterProvider } from 'tanstack/react-router-dom';
import { useEffect } from 'react';
Imports the necessary hooks and components from TanStack Router and React.
const ProtectedRoute = ({ children }) => {
const auth = useAuth(); // Custom hook to check authentication
if (!auth.user) {
// Replace with the route you want unauthenticated users to be redirected to
return <Navigate to="/login" replace />;
}
return children;
};
Defines a ProtectedRoute component that checks the user's authentication status. Redirects unauthenticated users to the login page.
const router = createBrowserRouter([
{
path: '/',
element: <Home />,
errorElement: <NotFound />,
children: [
{
path: 'protected',
element: (
<ProtectedRoute>
<ProtectedPage />
</ProtectedRoute>
),
},
],
},
]);
Creates a router instance with a protected route. Access to the 'protected' path requires authentication.
function App() {
return <RouterProvider router={router} />;
}
Defines the main App component that renders the router using RouterProvider.