T
TanStack3w ago
genetic-orange

Better-Auth Integration

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 their docs, in the usage tips they say: We recommend using the client SDK or authClient to handle authentication, rather than server actions with auth.api And in their nextjs demo they 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 || [];
},
});
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());
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
better-auth/demo/nextjs at canary · better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?