TanStackT
TanStack11mo ago
18 replies
worthy-rose

How to make beforeLoad hook run once in root route in Tanstack Start?

Hey there. As the title says, I have a beforeLoad hook in root route which returns the user session and color theme in the context, which I use in another pathless (_authed) file to redirect the unauthenticated users. The thing is that for example, when I am trying to navigate from /settings/profile to /settings/security, this beforeLoad hook runs again on the client. Every single route match triggers this hook. So far, I tried some properties from tanstack router such as (staleTime, gcTime, shouldReload), but did not work around. It seems like they only work with the loader() hook.
beforeLoad: async () => {
    try {
      const [theme, session] = await Promise.all([getTheme(), getSession()]);

      return {
        theme,
        session,
        isAuthenticated: !!session,
      };
    } catch {
      return { theme: ThemeEnum.Enum.dark, session: null, isAuthenticated: false };
    }
  },


export const Route = createFileRoute("/_authed")({
  beforeLoad: ({ context }) => {
    if (!context.isAuthenticated) {
      throw redirect({ href: "/" });
    }
  },
});
Was this page helpful?