Creating Protected Routes in SPAs
Explain how to create protected routes with TanStack Router that require user authentication, including redirect logic for unauthenticated users.
import { createBrowserRouter, Route } from 'tanstack-router';
import { authGuard } from './authGuard';
Import necessary modules from TanStack Router and an example authGuard function that will check if a user is authenticated.
const router = createBrowserRouter([
{
path: '/',
element: <Home />,
},
{
path: '/protected',
element: <ProtectedPage />, // This is the protected route
loader: authGuard, // The auth guard function used as a loader for the protected route
},
]);
Define the router with routes. The `/protected` route uses the `authGuard` function as a loader to check authentication.
function authGuard({ navigation }) {
if (!isUserAuthenticated()) {
// If user is not authenticated, redirect to login
navigation.navigate('/login');
}
}
Define the `authGuard` function, which checks if the user is authenticated. If not, it redirects the user to the `/login` route.
function isUserAuthenticated() {
// Implementation of user authentication check (e.g., check a cookie or local storage)
return !!localStorage.getItem('userToken');
}
Implement a simple `isUserAuthenticated` function that checks for user authentication (e.g., through localStorage).