Modularizing Routes for Scalability and Maintainability
Explain how to organize and modularize routes in a scalable fashion using TanStack Router, highlighting the approach to defining nested routes and route guards for maintaining application security.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
import { authenticateUser } from './auth';
Import necessary functions and components from TanStack Router and an authentication utility function.
const authGuard = async ({ navigation }) => {
if (!authenticateUser()) {
return navigation.redirect('/login');
}
};
Define an authentication guard that redirects unauthenticated users to the login page.
const dashboardRoutes = [
{ path: 'overview', element: <DashboardOverview /> },
{ path: 'reports', element: <DashboardReports /> }
];
Define routes for the dashboard module as an array of route objects.
const rootRouter = createBrowserRouter([
{
path: '/',
element: <App />,
children: [
{ path: 'login', element: <Login /> },
{
path: 'dashboard/*',
element: <Dashboard />,
loader: authGuard,
children: dashboardRoutes
}
]
}
]);
Create the root router with nested routes for the application, including an authentication guard for the dashboard module.
function App() {
return <RouterProvider router={rootRouter} />;
}
Define the main application component that renders the router.