Better-Auth with Tanstack Start + Tanstack Query

I have successfully refactored the better-auth nextjs demo to tanstack start
https://github.com/better-auth/better-auth/tree/canary/demo/nextjs

But I have a question:

In the docs, in the usage tips it is stated that:

We recommend using the client SDK or authClient to handle authentication, rather than server actions with auth.api

And in the nextjs demo,we have this useQuery:
const { data: users, isLoading: isUsersLoading } = useQuery({
        queryKey: ["users"],
        queryFn: async () => {
            const data = await client.admin.listUsers(
                {
                    query: {
                        limit: 10,
                        sortBy: "createdAt",
                        sortDirection: "desc",
                    },
                },
                {
                    throw: true,
                },
            );
            return data?.users || [];
        },
    });

My question is: should I replace it with useSuspenseQuery, and use a server function in the loader + ensureQueryData that fetches the user list using auth.api.listUsers
const fetchlistUsers = createServerFn({ method: 'GET' }).handler(async () => {
    const users = await auth.api.listUsers({
        query: {
            limit: 50,
            sortBy: 'createdAt',
            sortDirection: 'desc',
        },
        headers: await getWebRequest().headers,
    });

    return users?.users;
});

const listUsersQueryOptions = () =>
    queryOptions({
        queryKey: ['users'],
        queryFn: () => fetchlistUsers(),
    });

export const Route = createFileRoute('/_auth/_pathlessLayout/admin')({
    loader: async ({ context }) => {
        await context.queryClient.ensureQueryData(listUsersQueryOptions());
    },
    component: AdminDashboard,
});
// in the component
const { data: users = [] } = useSuspenseQuery(listUsersQueryOptions());
GitHub
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
Was this page helpful?