Protected Routes with Authentication
Exhibit how to implement protected routes that require authentication before access is granted, using TanStack Router guards or similar mechanisms to redirect unauthenticated users.
import { createBrowserRouter, createRoutesFromElements, Route, RouterProvider } from 'tanstack-router-react';
import { LoginPage, HomePage, Dashboard } from './components';
import { checkAuth } from './auth';
Imports necessary components and functions from TanStack Router, your application's components, and your authentication check function.
function RequireAuth({ children }) {
if (!checkAuth()) {
// Redirect to login if not authenticated
return <Navigate to="/login" replace />;
}
return children;
}
Defines a 'RequireAuth' component that checks if a user is authenticated. If not authenticated, it redirects the user to the login page. Otherwise, it renders the children components.
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/dashboard" element={<RequireAuth><Dashboard /></RequireAuth>} />
)
);
Creates a router instance with routes configured for the home page, login page, and a protected dashboard route. The dashboard route is wrapped in the 'RequireAuth' component to enforce authentication.
function App() {
return <RouterProvider router={router} />;
}
Defines the main App component that renders the RouterProvider with the configured router, effectively setting up routing for the application.