BETTER-AUTH. UI
Integrations

TanStack Start

Integrate Better Auth UI with TanStack Start

Prerequisites

Complete the Quick Start guide first.

Integration

Configure AuthProvider

Configure AuthProvider with TanStack Router's navigation.

components/providers.tsx
import { AuthProvider } from "@better-auth-ui/heroui"
import { themePlugin } from "@better-auth-ui/heroui/plugins/theme"
import { Toast } from "@heroui/react"
import { useNavigate } from "@tanstack/react-router"
import { ThemeProvider, useTheme } from "next-themes"
import type { ReactNode } from "react"

import { authClient } from "@/lib/auth-client"

export function Providers({ children }: { children: ReactNode }) {
  const navigate = useNavigate()

  return (
    <ThemeProvider defaultTheme="system" enableSystem disableTransitionOnChange>
      <AuthProvider
        authClient={authClient}
        redirectTo="/settings/account"
        socialProviders={["github"]}
        navigate={navigate}
        plugins={[themePlugin({ useTheme })]}
      >
        {children}

        <Toast.Provider />
      </AuthProvider>
    </ThemeProvider>
  )
}

The navigate prop connects Better Auth UI to TanStack Router. It accepts { to, replace } options.

Update the Root Route

Wrap your application with the Providers component in your root route.

routes/__root.tsx
import { TanStackDevtools } from "@tanstack/react-devtools"
import type { QueryClient } from "@tanstack/react-query"
import {
  createRootRouteWithContext,
  HeadContent,
  Scripts
} from "@tanstack/react-router"
import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools"
import type { ReactNode } from "react"
import { Header } from "@/components/header"
import { Providers } from "@/components/providers"
import appCss from "@/styles/app.css?url"

export const Route = createRootRouteWithContext<{
  queryClient: QueryClient
}>()({
  head: () => ({
    meta: [
      {
        charSet: "utf-8"
      },
      {
        name: "viewport",
        content: "width=device-width, initial-scale=1"
      },
      {
        title: "Start HeroUI Example"
      }
    ],
    links: [
      {
        rel: "stylesheet",
        href: appCss
      }
    ]
  }),
  shellComponent: RootDocument
})

function RootDocument({ children }: { children: ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <HeadContent />
      </head>

      <body className="antialiased min-h-svh flex flex-col">
        <Providers>
          <Header />

          {children}
        </Providers>

        <TanStackDevtools
          config={{
            position: "bottom-right"
          }}
          plugins={[
            {
              name: "TanStack Router",
              render: <TanStackRouterDevtoolsPanel />
            }
          ]}
        />

        <Scripts />
      </body>
    </html>
  )
}

Create the Auth Page

Create a dynamic auth page that renders the appropriate authentication view based on the path:

routes/auth/$path.tsx
import { viewPaths } from "@better-auth-ui/core"
import { Auth } from "@better-auth-ui/heroui"
import { magicLinkPlugin } from "@better-auth-ui/heroui/plugins/magic-link"
import { createFileRoute, notFound } from "@tanstack/react-router"

/** Keep in sync with `magicLinkPlugin(...)` in `providers.tsx` if you customize `path`. */
const validAuthPathSegments = new Set([
  ...Object.values(viewPaths.auth),
  magicLinkPlugin().viewPaths.auth.magicLink
])

export const Route = createFileRoute("/auth/$path")({
  beforeLoad({ params: { path } }) {
    if (!validAuthPathSegments.has(path)) {
      throw notFound()
    }
  },
  component: AuthPage
})

function AuthPage() {
  const { path } = Route.useParams()

  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. Validate the segment against viewPaths.settings.

Return a 404 response for an unknown path.

routes/settings/$path.tsx
import { ensureSession, viewPaths } from "@better-auth-ui/core"
import { ensureSessionServer } from "@better-auth-ui/core/server"
import { Settings } from "@better-auth-ui/heroui"
import { organizationPlugin } from "@better-auth-ui/heroui/plugins/organization"
import { createFileRoute, notFound, redirect } from "@tanstack/react-router"
import { createIsomorphicFn } from "@tanstack/react-start"
import { getRequestHeaders } from "@tanstack/react-start/server"

import { auth } from "@/lib/auth"
import { authClient } from "@/lib/auth-client"

/** Same pattern as magic-link: spread plugin `viewPaths.settings` into the allowed segment set. */
const validSettingsPaths = [
  ...Object.values(viewPaths.settings),
  ...Object.values(organizationPlugin().viewPaths.settings)
]

export const Route = createFileRoute("/settings/$path")({
  async beforeLoad({ params: { path }, context: { queryClient }, location }) {
    if (!validSettingsPaths.includes(path)) {
      throw notFound()
    }

    const ensureSessionIso = createIsomorphicFn()
      .server(() =>
        ensureSessionServer(queryClient, auth, { headers: getRequestHeaders() })
      )
      .client(() => ensureSession(queryClient, authClient))

    const session = await ensureSessionIso()

    if (!session) {
      throw redirect({
        to: "/auth/$path",
        params: { path: "sign-in" },
        search: { redirectTo: location.href }
      })
    }

    return { session }
  },
  component: SettingsPage
})

function SettingsPage() {
  const { path } = Route.useParams()

  return (
    <div className="w-full max-w-3xl mx-auto p-4 md:p-6">
      <Settings path={path} />
    </div>
  )
}

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 (beforeLoad)

For an SSR route, read the session in beforeLoad. This redirects unauthenticated users before a component renders.

Use createIsomorphicFn to call ensureSessionServer on the server and ensureSession in the browser. The server helper calls auth.api directly.

Both helpers use authQueryKeys.session in the same TanStack Query cache. Child useSession calls can reuse the hydrated session.

routes/dashboard.tsx
import { ensureSession } from "@better-auth-ui/core"
import { ensureSessionServer } from "@better-auth-ui/core/server"
import { createFileRoute, Link, redirect } from "@tanstack/react-router"
import { createIsomorphicFn } from "@tanstack/react-start"
import { getRequestHeaders } from "@tanstack/react-start/server"

import { auth } from "@/lib/auth"
import { authClient } from "@/lib/auth-client"

export const Route = createFileRoute("/dashboard")({
  async beforeLoad({ context: { queryClient }, location }) {
    const ensureSessionIso = createIsomorphicFn()
      .server(() =>
        ensureSessionServer(queryClient, auth, { headers: getRequestHeaders() })
      )
      .client(() => ensureSession(queryClient, authClient))

    const session = await ensureSessionIso()

    if (!session) {
      throw redirect({
        to: "/auth/$path",
        params: { path: "sign-in" },
        search: { redirectTo: location.href }
      })
    }

    return { session }
  },
  component: Dashboard
})

function Dashboard() {
  const { session } = Route.useRouteContext()

  return (
    <div className="flex flex-col items-center my-auto">
      <h1 className="text-2xl">Hello, {session.user.email}</h1>

      <Link to="/auth/$path" params={{ path: "sign-out" }}>
        Sign Out
      </Link>
    </div>
  )
}

Child routes and components can read the returned { session } through Route.useRouteContext().

ensureSessionServer also adds the session to the query cache during SSR. Downstream useSession calls then render without a loading state.

Reactive protection and prerendered routes (useAuthenticate)

beforeLoad only runs when the route loads. It does 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:

  1. Alongside beforeLoad for server-rendered routes, as a second layer that keeps the UI in sync after the initial load.
  2. On its own for prerendered or client-rendered routes that have no server-side session access.
routes/dashboard.tsx
import { authClient } from "@/lib/auth-client"
import { useAuthenticate } from "@better-auth-ui/react"
import { Spinner } from "@heroui/react"
import { createFileRoute, Link } from "@tanstack/react-router"

export const Route = createFileRoute("/dashboard")({
  component: Dashboard
})

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 to="/auth/$path" params={{ path: "sign-out" }}>
        Sign Out
      </Link>
    </div>
  )
}

beforeLoad protects the initial render and hydrates the session. Then useAuthenticate reacts to later session changes.

Example Project

For a complete example, see start-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

On this page