T
TanStack3w ago
provincial-silver

Adding authentication leads to performance issues and unneccessary api calls

In my src/routes/(protected)/admin/route.tsx layout file, I call
export const Route = createFileRoute("/(protected)/admin")({
beforeLoad: async () => {
const user = await getLoggedInUser(); ### Call to auth provider
if (!user) {
throw redirect({ to: "/admin/login" });
}
return { user };
},
component: AdminLayoutComponent,
});
export const Route = createFileRoute("/(protected)/admin")({
beforeLoad: async () => {
const user = await getLoggedInUser(); ### Call to auth provider
if (!user) {
throw redirect({ to: "/admin/login" });
}
return { user };
},
component: AdminLayoutComponent,
});
Then when navigating to a nested routedashboard.tsx or users.tsx it calls again the beforeLoad function as I see those calls in the logs. Shouldn't this somehow been cached? At the moment there are a bunch of api calls against the auth provider made only through navigation. Then, if a server function is performed another call to the auth provider is made as through an authMiddleware. I assume there is a better way to do this in tanstack start.
6 Replies
firm-tan
firm-tan3w ago
beforeLoad is not cached you can cache it yourself using e.g. query
provincial-silver
provincial-silverOP3w ago
Ok, thx. Then the docs are a bit misleading as they propose using beforeload which acts as a middleware for protected routes
extended-salmon
extended-salmon3w ago
yeah beforeLoad is the right place to do this, you just add caching yourself in beforeLoad example: https://github.com/dotnize/react-tanstarter/blob/main/src%2Froutes%2F%28authenticated%29%2Froute.tsx
GitHub
react-tanstarter/src/routes/(authenticated)/route.tsx at main · do...
🏝️ minimal TanStack Start template with Better Auth, Drizzle ORM, shadcn/ui - dotnize/react-tanstarter
optimistic-gold
optimistic-gold3w ago
is it not generally a bad idea to cache authenticated related stuff? what if you get a cached user back, but the session is already expired for example. This could lead to bad user experience.
provincial-silver
provincial-silverOP2w ago
I also thought of that. So guess it is advised to verify for each route if the user session is still valid
extended-salmon
extended-salmon2w ago
lots of factors here e.g. cache duration. 5 mins or less shouldnt be that bad plus it's only for routes. in server functions/api routes you should always use a fresh uncached session

Did you find this page helpful?