Next.js
Integrate Better Auth UI with Next.js
Prerequisites
Complete the Quick Start guide first.
Integration
Create the QueryClient
Create a shared QueryClient factory with the standard Next.js SSR pattern. Create one client per server request and one browser singleton.
import { environmentManager, QueryClient } from "@tanstack/react-query"
function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 5000
}
}
})
}
let browserQueryClient: QueryClient | undefined
export function getQueryClient() {
if (environmentManager.isServer()) {
// Server: always make a new query client
return makeQueryClient()
} else {
// Browser: make a new query client if we don't already have one
// This is very important, so we don't re-make a new client if React
// suspends during the initial render. This may not be needed if we
// have a suspense boundary BELOW the creation of the query client
if (!browserQueryClient) browserQueryClient = makeQueryClient()
return browserQueryClient
}
}On the server, each call returns a new QueryClient. This design keeps the request cache separate for each user.
In the browser, the singleton preserves the React Query cache across navigation. It also gives HydrationBoundary a stable hydration target.
Configure AuthProvider
Configure AuthProvider with Next.js navigation. Then wrap it in QueryClientProvider so it uses the shared client.
"use client"
import { AuthProvider } from "@better-auth-ui/heroui"
import { deleteUserPlugin } from "@better-auth-ui/heroui/plugins/delete-user"
import { Toast } from "@heroui/react"
import { QueryClientProvider } from "@tanstack/react-query"
import { useRouter } from "next/navigation"
import type { ReactNode } from "react"
import { authClient } from "@/lib/auth-client"
import { getQueryClient } from "@/lib/query-client"
export function Providers({ children }: { children: ReactNode }) {
const router = useRouter()
const queryClient = getQueryClient()
return (
<QueryClientProvider client={queryClient}>
<AuthProvider
authClient={authClient}
redirectTo="/settings/account"
socialProviders={["google", "github"]}
navigate={({ to, replace }) =>
replace ? router.replace(to) : router.push(to)
}
plugins={[deleteUserPlugin()]}
>
{children}
<Toast.Provider />
</AuthProvider>
</QueryClientProvider>
)
}The navigate prop connects Better Auth UI to Next.js navigation. It accepts { to, replace } options.
Update the Root Layout
Wrap your application with the Providers component in your root layout.
import type { Metadata } from "next"
import { Geist, Geist_Mono } from "next/font/google"
import { ThemeProvider } from "next-themes"
import type { ReactNode } from "react"
import "@/styles/app.css"
import { Header } from "@/components/header"
import { Providers } from "@/components/providers"
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"]
})
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"]
})
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app"
}
export default function RootLayout({
children
}: Readonly<{
children: ReactNode
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased min-h-svh flex flex-col`}
>
<ThemeProvider
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<Providers>
<Header />
{children}
</Providers>
</ThemeProvider>
</body>
</html>
)
}Create the Auth Page
Create a dynamic auth page that renders the appropriate authentication view based on the path:
import { viewPaths } from "@better-auth-ui/core"
import { Auth } from "@better-auth-ui/heroui"
import { notFound } from "next/navigation"
export default async function AuthPage({
params
}: {
params: Promise<{
path: string
}>
}) {
const { path } = await params
if (!Object.values(viewPaths.auth).includes(path)) {
notFound()
}
return (
<div className="flex justify-center my-auto p-4 md:p-6">
<Auth path={path} />
</div>
)
}The built-in viewPaths.auth object contains the standard authentication paths. These include redirect, sign-in, sign-up, sign-out, and password recovery paths.
If a plugin adds authentication paths, spread its viewPaths.auth into the validation set. See the Magic Link guide for an example.
Create the Settings page
Create a dynamic settings route for the URL segment.
The async server component validates the path and session. It redirects unauthenticated users before it sends HTML.
The component also adds the session query to HydrationBoundary. As a result, child hooks skip their loading state during hydration.
import { viewPaths } from "@better-auth-ui/core"
import { ensureSessionServer } from "@better-auth-ui/core/server"
import { Settings } from "@better-auth-ui/heroui"
import { dehydrate, HydrationBoundary } from "@tanstack/react-query"
import { headers } from "next/headers"
import { notFound, redirect } from "next/navigation"
import { auth } from "@/lib/auth"
import { getQueryClient } from "@/lib/query-client"
export default async function SettingsPage({
params
}: {
params: Promise<{
path: string
}>
}) {
const { path } = await params
if (!Object.values(viewPaths.settings).includes(path)) {
notFound()
}
const requestHeaders = await headers()
const queryClient = getQueryClient()
const session = await ensureSessionServer(queryClient, auth, {
headers: requestHeaders
})
if (!session) {
redirect(
`/auth/sign-in?redirectTo=${encodeURIComponent(`/settings/${path}`)}`
)
}
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<div className="w-full max-w-3xl mx-auto p-4 md:p-6">
<Settings path={path} />
</div>
</HydrationBoundary>
)
}The built-in viewPaths.settings object contains account and security. If a plugin adds settings views, spread its viewPaths.settings into the validation set.
Protecting Routes
Better Auth UI provides separate protection patterns for server-rendered and prerendered routes.
Server-rendered routes (async server component)
For an SSR route, read the session in an async server component. This redirects unauthenticated users before the server streams HTML.
Call ensureSessionServer from @better-auth-ui/core/server with a separate QueryClient for each request. This helper calls auth.api directly.
Wrap the rendered children in HydrationBoundary. Then downstream useSession calls read authQueryKeys.session from the hydrated cache.
import { ensureSessionServer } from "@better-auth-ui/core/server"
import { dehydrate, HydrationBoundary } from "@tanstack/react-query"
import { headers } from "next/headers"
import Link from "next/link"
import { redirect } from "next/navigation"
import { auth } from "@/lib/auth"
import { getQueryClient } from "@/lib/query-client"
export default async function Dashboard() {
const queryClient = getQueryClient()
const session = await ensureSessionServer(queryClient, auth, {
headers: await headers()
})
if (!session) {
redirect("/auth/sign-in?redirectTo=/dashboard")
}
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<div className="flex flex-col items-center my-auto">
<h1 className="text-2xl">Hello, {session.user.email}</h1>
<Link href="/auth/sign-out">Sign Out</Link>
</div>
</HydrationBoundary>
)
}ensureSession adds the session to the query cache during SSR. HydrationBoundary sends this state to the browser.
As a result, child components that call useSession render without a loading state.
If a client component outside the protected route reads the session, prefetch the session in its server parent. Then wrap that subtree in HydrationBoundary.
This pattern commonly applies to a header or sidebar that contains UserButton. Without the prefetch, the component starts a new browser request.
See the example header for the complete pattern.
Reactive protection and prerendered routes (useAuthenticate)
Server-side session checks only occur when the route loads. They do not detect session changes while the page remains mounted.
These changes include token expiration, sign-out in another tab, and server-side session revocation. Prerendered and client-rendered routes also have no server check.
The useAuthenticate hook covers both cases. It subscribes to useSession and redirects the user when the session ends.
The hook preserves the current URL in the redirectTo query parameter.
Use it in two situations:
- Alongside an async server component for server-rendered routes, as a second layer that keeps the UI in sync after the initial load.
- On its own for prerendered or client-rendered routes that have no server-side session access.
"use client"
import { authClient } from "@/lib/auth-client"
import { useAuthenticate } from "@better-auth-ui/react"
import { Spinner } from "@heroui/react"
import Link from "next/link"
export default function Dashboard() {
const { data: session } = useAuthenticate(authClient)
if (!session) {
return (
<div className="flex justify-center my-auto">
<Spinner color="current" />
</div>
)
}
return (
<div className="flex flex-col items-center my-auto">
<h1 className="text-2xl">Hello, {session.user.email}</h1>
<Link href="/auth/sign-out">Sign Out</Link>
</div>
)
}The async server component protects the initial render and hydrates the session. Then useAuthenticate reacts to later session changes.
Example Project
For a complete example, see next-heroui-example in the repository.
Next Steps
Read about the shared React hooks and query primitives that power each Better Auth UI component.
Last updated on