BETTER-AUTH. UI
Queries

useSession

Read, prefetch, and invalidate the current authenticated session.

Usage

import { authClient } from "@/lib/auth-client"
import { useSession } from "@better-auth-ui/react"

// Most common
const { data: session } = useSession(authClient)

// React Query options
const { data: session } = useSession(authClient, { staleTime: 30_000 })

// Better Auth params
const { data: session } = useSession(authClient, {
  query: { disableCookieCache: true }
})

// Both in one object
const { data: session } = useSession(authClient, {
  query: { disableCookieCache: true },
  staleTime: 30_000
})

Options factory

import { sessionOptions } from "@better-auth-ui/core"
import { useQuery } from "@tanstack/react-query"

const { data: session } = useQuery(sessionOptions(authClient))

Server-side prefetching

For client and router loaders that already have an authClient, use the helpers from @better-auth-ui/core.

import { ensureSession, fetchSession, prefetchSession } from "@better-auth-ui/core"

await ensureSession(queryClient, authClient)
await prefetchSession(queryClient, authClient)
const session = await fetchSession(queryClient, authClient)

For server loaders, use @better-auth-ui/core/server. These helpers call your Better Auth server instance directly. Pass the request headers required by auth.api.getSession.

import { ensureSessionServer } from "@better-auth-ui/core/server"
import { getRequestHeaders } from "@tanstack/react-start/server"

import { auth } from "@/lib/auth"

const session = await ensureSessionServer(queryClient, auth, {
  headers: getRequestHeaders()
})

Both entrypoints share the same session query key, so server-prefetched data hydrates into client-side useSession.

Invalidation

import { sessionOptions } from "@better-auth-ui/core"

queryClient.invalidateQueries({
  queryKey: sessionOptions(authClient).queryKey
})

The shared key factory provides the same query key:

import { authQueryKeys } from "@better-auth-ui/core"

queryClient.invalidateQueries({ queryKey: authQueryKeys.session })

Client params

Prop

Type

Server params

Prop

Type

Last updated on

On this page