A TanStack React Query client for Better Auth.
npm install better-auth-react-queryA TanStack React Query client wrapper for Better Auth. This package transforms your Better Auth client into a TanStack Query-compatible client with full TypeScript support.
``bash`
npm install better-auth-react-queryor
yarn add better-auth-react-queryor
pnpm add better-auth-react-query
- @tanstack/react-query >= 5.0.0better-auth
- >= 1.4.0
First, create a query client from your Better Auth client:
`ts
import { createAuthQueryClient } from 'better-auth-react-query'
import { createAuthClient } from 'better-auth/react'
const authClient = createAuthClient()
const auth = createAuthQueryClient(authClient)
`
Methods starting with get or list are automatically treated as queries. Use queryOptions() to get TanStack Query compatible options:
`tsx
import { useQuery } from '@tanstack/react-query'
function Profile() {
const { data: session } = useQuery(auth.getSession.queryOptions())
return
For queries that require input parameters:
`tsx
const { data: user } = useQuery(
auth.admin.getUser.queryOptions({ query: { id: '123' } }),
)
`Passing query options:
`tsx
const { data: user } = useQuery(
auth.admin.getUser.queryOptions(
{ query: { id: '123' } },
{
staleTime: 100,
},
),
)
`$3
You can access query keys directly for cache invalidation:
`ts
import { useQueryClient } from '@tanstack/react-query'const queryClient = useQueryClient()
// Invalidate the session query
queryClient.invalidateQueries({ queryKey: auth.getSession.queryKey() })
// With parameters
queryClient.invalidateQueries({
queryKey: auth.admin.getUser.queryKey({ query: { id: : '123'} }),
})
`$3
All other methods are treated as mutations. Use
mutationOptions() to get TanStack Query compatible options:`tsx
import { useMutation } from '@tanstack/react-query'function SignInForm() {
const signIn = useMutation(auth.signIn.email.mutationOptions())
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
const formData = new FormData(e.currentTarget)
signIn.mutate({
email: formData.get('email') as string,
password: formData.get('password') as string,
})
}
return (
)
}
`$3
Errors from Better Auth are automatically thrown, making them compatible with TanStack Query's error handling:
`tsx
const signIn = useMutation(
auth.signIn.email.mutationOptions({
onError: (error) => {
console.error('Sign in failed:', error.message)
},
}),
)
`TypeScript
The package provides full type inference. All query and mutation options are properly typed based on your Better Auth client configuration:
`ts
// Types are inferred from your auth client
const { data } = useQuery(auth.getSession.queryOptions())
// data is typed as your session typeconst signUp = useMutation(auth.signUp.email.mutationOptions())
// signUp.mutate() expects the correct input type
``Apache-2.0