TanStackT
TanStack16mo ago
9 replies
dual-salmon

Cookie based authentication approach

Hello all. I have a cookie based authentication approach. In my login page and in my _app layout i have a
beforeLoad
function like this:

login.tsx

beforeLoad: async ({ context, search }) => {
    const user = await context.queryClient.ensureQueryData({
      queryKey: ['auth-user'],
      queryFn: AuthService.me,
      staleTime: Infinity,
    });

    if (user) {
      throw redirect({
        to: search.redirect,
      });
    }
  },


_app.tsx
 beforeLoad: async ({ context, location }) => {
    const user = await context.queryClient.ensureQueryData({
      queryKey: ['auth-user'],
      queryFn: AuthService.me,
      staleTime: Infinity,
    });

    if (!user) {
      throw redirect({
        to: '/login',
        search: {
          // Use the current location to power a redirect after login
          // (Do not use `router.state.resolvedLocation` as it can
          // potentially lag behind the actual current location)
          redirect: location.href,
        },
      });
    }
  },


Is there a better approach on this using tanstack query & tanstack router?
Was this page helpful?