> This page location: Auth > Quickstarts > TanStack Router
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

> Summary: Managed Better Auth quick start for TanStack Router (file-router) using the `@neon/auth` SDK and Better Auth UI's shadcn/ui components (`<Auth>`, `<UserButton>`, `<Settings>`). Use this page when you need sign-in, sign-up, account settings, and route protection without writing custom auth UI. User profiles are stored automatically in the `neon_auth.user` table in your database.

# Use Managed Better Auth with TanStack Router

Set up authentication using pre-built UI components

Last updated: 2026-11-05

**Tip: Using an AI coding tool?**

Run `npx neon@latest init` to connect the [Neon MCP server](https://neon.com/docs/ai/neon-mcp-server) and [Agent Skills](https://neon.com/docs/ai/agent-skills) for Managed Better Auth. See [Set up with your AI editor](https://neon.com/docs/auth/about#set-up-with-your-ai-editor) for MCP tools, example prompts, and how skills help wire auth into your app.

## Create a Neon project with Auth enabled

If you don't have a Neon project yet, create one at [console.neon.tech](https://console.neon.tech).

In the Neon Console, open the **Better Auth** page and click **Enable Auth**.

You can then find your Auth URL on the Configuration tab. Copy this URL - you'll need it in the next step.

## Create a TanStack Router app

Create a new TanStack Router app using the file-router template.

```bash filename="Terminal"
npx create-tsrouter-app@latest my-app --template file-router --tailwind
```

## Install the Managed Better Auth SDK and UI

Install the Managed Better Auth SDK, initialize [shadcn/ui](https://ui.shadcn.com), and add [Better Auth UI](https://better-auth-ui.com)'s auth views, user menu, and settings pages. The shadcn CLI copies the components into `src/components/`.

The shadcn CLI installs the npm `latest` tag of `better-auth`, so run `npm i better-auth@~1.7.12` after the last `shadcn add` to match the version `@neon/auth` uses and keep one copy.

To use the examples below, choose TypeScript, `src/styles.css` as the global CSS file, `@/components` as the component alias, and no React Server Components. You can use the defaults for the other prompts.

```bash filename="Terminal"
cd my-app
npm install @neon/auth@latest
npx shadcn@latest init
npx shadcn@latest add @better-auth-ui/auth @better-auth-ui/user-button @better-auth-ui/settings
npm i better-auth@~1.7.12
```

## Set up environment variables

Create a `.env` file in your project root and add your Auth URL:

**Note:** Replace the URL with your actual Auth URL from the Neon Console.

```bash filename=".env"
VITE_NEON_AUTH_URL=https://ep-xxx.neonauth.us-east-1.aws.neon.tech/neondb/auth
```

## Add trusted origins

Managed Better Auth only redirects to [trusted domains](https://neon.com/docs/auth/guides/configure-domains). Add the origin your app runs on, `http://localhost:3000` for local development, and your production origin when you deploy. Otherwise sign-in redirects and email verification links fail.

```bash filename="Terminal"
neon neon-auth domain add http://localhost:3000
neon neon-auth domain add https://myapp.com
```

## Configure the auth client

Create a `src/auth.ts` file to initialize the auth client:

**Tip: Using Auth and Data API together?**

This quick start uses the standalone Auth client. For one `createClient()` instance that derives both Auth and Data API URLs from a single Neon URL, see [`createClient()` initialization](https://neon.com/docs/reference/javascript-sdk#initializing).

```typescript filename="src/auth.ts"
import { createAuthClient } from '@neon/auth';
import { BetterAuthReactAdapter } from '@neon/auth/react/adapters';

export const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL, {
  adapter: BetterAuthReactAdapter({ fetchOptions: { credentials: 'include' } }),
});
```

## Create the Auth Provider

Wrap your application in a TanStack Query `QueryClientProvider` and the `AuthProvider` the shadcn CLI copied into `src/components/auth/`. This makes the auth state available to the UI components used throughout your app.

`navigate` receives the URL's `?redirectTo=` value after sign-in, so it checks the target before navigating. See [Validate redirect targets](https://neon.com/docs/auth/reference/ui-components#validate-redirect-targets). For the other props, see the [UI components reference](https://neon.com/docs/auth/reference/ui-components#provider-setup).

```tsx filename="src/routes/__root.tsx"
import { getSafeRedirectTo } from '@better-auth-ui/core';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Link, Outlet, createRootRoute, useRouter } from '@tanstack/react-router';
import type { ComponentProps } from 'react';
import { AuthProvider } from '@/components/auth/auth-provider';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
import { authClient } from '../auth';
import '../styles.css';

const queryClient = new QueryClient();

export const Route = createRootRoute({
  component: Root,
});

function Root() {
  const router = useRouter();
  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider
        authClient={authClient}
        emailAndPassword={{ requireEmailVerification: false }} // match your branch's setting
        navigate={({ to, replace }) => {
          const path = getSafeRedirectTo(to, window.location.origin);
          const target = path.startsWith('//') ? '/' : path;
          void router.navigate({ href: target, replace });
        }}
        Link={RouterLink}
        redirectTo="/"
      >
        <TooltipProvider>
          <Outlet />
        </TooltipProvider>
        <Toaster />
      </AuthProvider>
    </QueryClientProvider>
  );
}

// Better Auth UI passes an href with a query string, which `to` doesn't parse.
function RouterLink({
  href,
  to: _to,
  ...props
}: { href: string; to?: string } & Omit<ComponentProps<'a'>, 'href'>) {
  const url = new URL(href, window.location.origin);
  return (
    <Link
      to={url.pathname}
      search={Object.fromEntries(url.searchParams)}
      hash={url.hash.slice(1)}
      {...props}
    />
  );
}
```

## Create the Auth page

Create a route to handle authentication views (sign in, sign up, etc.). Create `src/routes/auth.$path.tsx`.

This route also serves `/auth/redirect`, which navigates on its own. Add the redirect check from [Validate redirect targets](https://neon.com/docs/auth/reference/ui-components#validate-redirect-targets) to `src/components/auth/auth-redirect.tsx`.

```tsx filename="src/routes/auth.$path.tsx"
import { createFileRoute } from '@tanstack/react-router';
import { Auth } from '@/components/auth/auth';

export const Route = createFileRoute('/auth/$path')({
  component: AuthPage,
});

function AuthPage() {
  const { path } = Route.useParams();
  return (
    <main className="flex min-h-screen items-center justify-center p-4">
      <Auth path={path} />
    </main>
  );
}
```

## Create the Settings page

Create a route for the account and security settings. The user menu links to it. Create `src/routes/settings.$path.tsx`:

```tsx filename="src/routes/settings.$path.tsx"
import { createFileRoute } from '@tanstack/react-router';
import { Settings } from '@/components/auth/settings/settings';

export const Route = createFileRoute('/settings/$path')({
  component: SettingsPage,
});

function SettingsPage() {
  const { path } = Route.useParams();
  return (
    <main className="mx-auto w-full max-w-3xl p-4">
      <Settings path={path} />
    </main>
  );
}
```

## Protect your routes

Read the session with `useSession`, and send signed-out visitors to the sign-in page. Wait until the session query has finished fetching: right after sign-up, the cached result is still signed out while the new session loads.

Update `src/routes/index.tsx` to protect the home page:

```tsx filename="src/routes/index.tsx"
import { useSession } from '@better-auth-ui/react';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { useEffect } from 'react';
import { UserButton } from '@/components/auth/user/user-button';
import { authClient } from '@/auth';

export const Route = createFileRoute('/')({
  component: Home,
});

function Home() {
  const navigate = useNavigate();
  const { data, isFetching } = useSession(authClient);
  const signedOut = !data && !isFetching;

  useEffect(() => {
    if (signedOut) void navigate({ to: '/auth/$path', params: { path: 'sign-in' } });
  }, [signedOut, navigate]);

  if (!data) return null;

  return (
    <main className="flex min-h-screen flex-col items-center justify-center gap-8 p-4">
      <div className="text-center">
        <h1>Welcome!</h1>
        <p>You're successfully authenticated.</p>
        <UserButton />
        <p className="mt-4 font-medium text-gray-700 dark:text-gray-200">Session and User Data:</p>
        <pre className="mx-auto w-full max-w-full overflow-x-auto rounded-lg bg-gray-900 p-4 text-left text-sm break-words whitespace-pre-wrap text-gray-100 sm:max-w-2xl">
          <code>{JSON.stringify({ session: data.session, user: data.user }, null, 2)}</code>
        </pre>
      </div>
    </main>
  );
}
```

## Start your app

Start the development server, then open [http://localhost:3000](http://localhost:3000). You'll be redirected to the sign-in page.

```bash filename="Terminal"
npm run dev
```

## See your users in the database

As users sign up, their profiles are stored in your Neon database in the `neon_auth.user` table.

Query your users table in the SQL Editor to see your new users:

```sql filename="SQL Editor"
SELECT * FROM neon_auth.user;
```

## Next steps

- [Add email verification](https://neon.com/docs/auth/guides/email-verification)
- [Learn how to branch your auth](https://neon.com/docs/auth/branching-authentication)
- [More example apps](https://neon.com/docs/auth/about#example-applications)

---

## Related docs (Quickstarts)

- [Next.js](https://neon.com/docs/auth/quick-start/nextjs-api-only)
- [React](https://neon.com/docs/auth/quick-start/react)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/docs/auth/quick-start/tanstack-router"}` to https://feedback.neon.tech/ (no auth required).
