TanStackT
TanStack9mo ago
14 replies
dual-salmon

How to handle throw redirect() from server functions when using ensureQueryData?

I have a server function defined like this:
export const getCurrentUserFn = createServerFn({ method: "GET" }).handler(
  async () => {
    throw redirect({ to: "/" });
  },
);


I'm using it in my route like this:
const currentUserOptions = () =>
  queryOptions({
    queryKey: ["current-user"],
    queryFn: getCurrentUserFn,
  });

export const Route = createFileRoute("/url")({
  component: RouteComponent,
  loader: async ({ context }) => {
    await context.queryClient.ensureQueryData(currentUserOptions());
  },
});

The problem is that the redirection thrown from the server function (throw redirect(...)) is not being handled—it simply does nothing. I understand that I could use useServerFn() to catch the redirect, but doing so would prevent me from using ensureQueryData.
How can I properly handle the redirection thrown by getCurrentUserFn in the loader, while still using ensureQueryData (or an alternative)?
Was this page helpful?