BETTER-AUTH. UI
Queries

useSession

Read, prefetch, and invalidate the current authenticated session.

Usage

import { useAuth, useSession } from "@better-auth-ui/react"

const { authClient } = useAuth()

// 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/react"
import { useQuery } from "@tanstack/react-query"

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

Server-side prefetching

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

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

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

For server loaders, import from @better-auth-ui/react/server. These helpers call your Better Auth server instance directly and require the request params passed to auth.api.getSession, typically request headers.

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

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

const session = await ensureSession(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/react"

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

Or, equivalently, via the shared key factory:

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