useAuthenticate
Session query that redirects unauthenticated users to sign-in.
useAuthenticate calls useSession and, once the query settles, redirects unauthenticated users to the configured sign-in path. The current URL is preserved as a redirectTo query parameter so the user lands back where they started after signing in.
Use this as the primary guard inside protected route components.
Usage
import { authClient } from "@/lib/auth-client"
import { useAuthenticate } from "@better-auth-ui/react"
export function AccountPage() {
const { data: session, isPending } = useAuthenticate(authClient)
if (isPending) return <Spinner />
if (!session) return null // navigating to sign-in
return <Account user={session.user} />
}The redirect uses basePaths.auth + viewPaths.auth.signIn from AuthProvider: override those to target a custom sign-in view.
Accepts the same arguments as useSession: see its Params.
First-render caveat
The redirect runs inside useEffect, so it is browser-only. During the first render, session is undefined and navigation has not started.
The protected interface can appear briefly before the browser mounts the component and redirects to sign-in.
You have two ways to handle this:
Gate on isPending (simplest)
Render a skeleton or spinner while the session query is pending, and null once it resolves to unauthenticated (the redirect is already in flight). This is what the Usage example does and is enough for most apps:
const { data: session, isPending } = useAuthenticate(authClient)
if (isPending) return <Skeleton />
if (!session) return null // navigating to sign-in
return <Account user={session.user} />No flash of protected content, no server work required: just a brief loading state on first mount. Works identically for SSR, client-rendered, and statically prerendered routes.
Pair with a server-side guard (no loading state)
To render the protected interface immediately without a skeleton, prefetch the session on the server. Then hydrate it into the query cache:
- Next.js: prefetch in a server component and wrap the subtree in
HydrationBoundary. See the Next.js integration guide. - TanStack Start: check the session in
beforeLoadon the route. See the TanStack Start integration guide.
The server-side check protects the first render. useAuthenticate redirects after token expiration, remote sign-out, or server-side session revocation.
Last updated on