I'm working on a project using @tanstack/react-router where I need to protect my admin pages. I've decided to use a layout to apply authentication restrictions to all children of the admin folder. Here's the setup:
For the admin layout located at routes/admin/_layout.tsx, I've implemented a check to redirect unauthenticated users to the login page:
import { Outlet, createFileRoute, redirect } from '@tanstack/react-router';
export const Route = createFileRoute('/admin/_layout')({
beforeLoad: async ({ context, location }) => {
if (!context.auth.isLogged()) {
throw redirect({
to: '/auth/login',
search: {
redirect: location.href,
},
});
}
},
component: () => (
<div style={{ backgroundColor: 'red' }}>
<Outlet />
</div>
),
});
And here's the admin page located at routes/admin/index.tsx:
import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute('/admin/')({
component: Index,
});
function Index() {
return (
<div className="p-2">
<h3>Welcome Home!</h3>
</div>
);
}
To test if the layout is working (independent of the redirection logic), I added a red background color. However, based on the testing, it appears that the layout itself is not being rendered.
Could anyone provide advice on why the layout is not applied to my admin pages? Is there something wrong with how I'm using createFileRoute or the layout setup itself?
SOLUTION
By upgrading @tanstack/react-router from ^1.19.8 to ^1.19.12 solved this issue