Contexts and Authenticated Routes deeper in the route tree #2032
-
I have a question, has anyone been able to implement Authenticated Routes that are deeper than the root level. The current docs for Route Context seems to encourage using Hooks or Context API inside of the Tanstack Router context to access data inside of the loader and beforeload functions for the Routes. I have an auth strategy where we have a general auth to get access to the app, and then we use ABAC to see which of the pages/resources you have access to. You can envision it like the file structure like: _auth.tsx So the _auth.tsx has the regular authenticated routes as described in the docs. However the permissions for the company lives inside of the _company_context layout route, which is a regular Context Provider. However, this means that i have no way of accessing the company context inside of the loader function for the hr.tsx route. In the hr.tsx i envision doing loader: async ({ context: { queryClient , companyContext}, params: { companyId } }) => {
if (!companyContext?.permissions.includes('company:ReadHR')) {
throw redirect({
to: '/overview',
});
} Do anyone have any suggestions for how to do protected routes when i do not have access to injecting the context at the RouteProvider or any other solutions for the general problem at hand 🙏🏽 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
can you please create a minimal complete example by forking one of the existing router examples on stackblitz? |
Beta Was this translation helpful? Give feedback.
-
I finally got back to this. For future reference, if anyone has issues that looks similar to what i had you can do this export const Route = createFileRoute('/monitoring')({
pendingComponent: PendingDownloadLoader,
loader: async ({ context: { queryClient } }) => {
const permissions = await queryClient.ensureQueryData(permissionsQueryOptions());
const hasAcces = hasAccessToMonitoring(permissions);
if (!hasAcces) {
throw redirect({
to: '/overview',
});
}
const defaultDate = getDefaultDate();
const defaultQueryInput = getDefaultMonitoringQueryInput(defaultDate);
const monitoringQuery = getMonitoringQueryOptions(defaultQueryInput);
await queryClient.ensureQueryData(monitoringQuery);
},
component: MonitoringPage,
}); This allows to have quite effective guards against unauthenticated and/or unauthorised access to components |
Beta Was this translation helpful? Give feedback.
Ok i found a solution that i think is quite sensible so i'll leave it here as an answer for other people.
I ended using Tanstack Query to write the permissions to a query with a static key, and make it update whenever the context is run.
So in the _company_context.tsx:
in the hr.tsx
l…