# Documentation ## Introduction URL: /docs A comprehensive authentication and authorization framework for TypeScript. Introduction Better Auth is a framework-agnostic, universal authentication and authorization framework for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities. Features - Framework Agnostic — Support for most popular frameworks - Email & Password — Built-in support for secure email and password authentication - Account & Session Management — Manage user accounts and sessions with ease - Built-In Rate Limiter — Built-in rate limiter with custom rules - Automatic Database Management — Automatic database management and migrations - Social Sign-on — Multiple social sign-on providers - Plugin Ecosystem — Even more capabilities with plugins Quick Start Get up and running in under 5 minutes: Next Steps - Read the Installation guide - Follow the Get Started guide - Explore Concepts --- ## Authentication URL: /docs/authentication Authentication methods — email/password, social sign-on, and more. Authentication Better Auth supports multiple authentication methods out of the box. You can enable one or many, and they all work together seamlessly. Available Methods | Method | Built-in | Plugin Required | | ---------------------- | -------- | ----------------- | | Email & Password | ✅ | — | | Social Sign-on (OAuth) | ✅ | — | | Magic Link | — | ✅ magic-link | | Passkeys (WebAuthn) | — | ✅ passkey | | Phone / SMS | — | ✅ phone-number | | Anonymous Auth | — | ✅ anonymous | Email & Password The most common authentication method. Enable it in your auth config: Password Hashing Better Auth uses Argon2id by default for password hashing — the most secure algorithm recommended by OWASP. You can also use bcrypt or scrypt: Social Sign-on See Social Sign-on for detailed provider setup. Choosing a Method - Email & Password — Best for most apps. Users expect it. Always offer alongside social. - Social Sign-on — Reduces friction. Great for B2C apps. Use Google + GitHub at minimum. - Magic Link — Passwordless simplicity. Good for internal tools and dashboards. - Passkeys — Most secure. Growing browser support. Great as a 2FA fallback. Deep Dives - Social Sign-on — Google, GitHub, Discord, and 20+ providers - Email Verification — Verify user emails with tokens --- ## Email Verification URL: /docs/authentication/email-verification Verify user email addresses with magic tokens and custom email templates. Email Verification Email verification ensures users own the email addresses they sign up with. This is critical for account recovery, preventing spam, and building trust. Enable Email Verification How It Works 1. User signs up with email and password 2. Better Auth generates a verification token 3. Your sendVerificationEmail function sends the email 4. User clicks the link, which hits /api/auth/verify-email?token=... 5. Better Auth verifies the token and marks the email as verified 6. User is optionally auto-signed in Configuration Options | Option | Type | Default | Description | | ----------------------------- | --------- | ------- | ---------------------------------- | | sendOnSignUp | boolean | true | Send verification email on sign up | | autoSignInAfterVerification | boolean | false | Auto sign-in after verification | | expiresIn | number | 3600 | Token expiry in seconds (1 hour) | Custom Email Templates With React Email With Resend Resend Verification Email Allow users to request a new verification email: Check Verification Status Always use a reputable email service (Resend, SendGrid, AWS SES) in production. Sending from localhost will likely land in spam folders. --- ## Social Sign-on URL: /docs/authentication/social-sign-on Set up OAuth social login with Google, GitHub, Discord, and more. Social Sign-on Better Auth supports 20+ social providers via OAuth 2.0. Users can sign in with a single click — no password required. Supported Providers | Provider | ID | Documentation | | ----------- | ----------- | ------------------------------------------------------------------------ | | Google | google | console.cloud.google.com | | GitHub | github | github.com/settings/developers | | Discord | discord | discord.com/developers | | Apple | apple | developer.apple.com | | Microsoft | microsoft | portal.azure.com | | Twitter / X | twitter | developer.twitter.com | | Facebook | facebook | developers.facebook.com | | LinkedIn | linkedin | linkedin.com/developers | | Spotify | spotify | developer.spotify.com | | Twitch | twitch | dev.twitch.tv | Configuration Server-Side Add providers to your auth config: Client-Side Trigger social sign-in from your UI: Setting Up Google OAuth 1. Go to Google Cloud Console 2. Create a new project or select an existing one 3. Navigate to APIs & Services → Credentials 4. Click Create Credentials → OAuth Client ID 5. Select Web application 6. Add authorized redirect URI: http://localhost:3000/api/auth/callback/google 7. Copy the Client ID and Client Secret to your .env Setting Up GitHub OAuth 1. Go to GitHub Developer Settings 2. Click New OAuth App 3. Set Homepage URL to http://localhost:3000 4. Set Authorization callback URL to http://localhost:3000/api/auth/callback/github 5. Copy the Client ID and generate a Client Secret Account Linking When a user signs in with a social provider and already has an account with the same email, Better Auth automatically links the accounts: Only enable account linking for providers you trust to verify email addresses. This prevents account takeover attacks. Custom Scopes Request additional permissions from providers: --- ## Basic Usage URL: /docs/basic-usage Learn the fundamental auth flows — sign up, sign in, and session management. Basic Usage This guide covers the essential authentication flows: creating accounts, signing in, managing sessions, and protecting routes. Create the Auth Client On the client side, create an auth client that communicates with your API: Sign Up Create a new user with email and password: Sign In Email & Password Social Sign-In Session Management Get Current Session Use the useSession hook in React components: Sign Out Protecting Routes Server-Side (Next.js) Use it in a server component: Client-Side Guard Quick Reference | Action | Method | | ---------------- | ----------------------------------------- | | Sign up | signUp.email({ email, password, name }) | | Sign in (email) | signIn.email({ email, password }) | | Sign in (social) | signIn.social({ provider }) | | Get session | useSession() hook | | Sign out | signOut() | | Server session | auth.api.getSession({ headers }) | Next Steps - Learn about Session Management in depth - Set up Social Sign-on providers - Add Two Factor Authentication for extra security --- ## Concepts URL: /docs/concepts Core concepts and architecture of Better Auth. Concepts Understanding these core concepts will help you get the most out of Better Auth and build robust authentication systems. Architecture Overview Better Auth follows a layered architecture: 1. Client SDK — Framework-specific hooks and utilities for the frontend 2. API Handler — HTTP endpoints that handle auth requests (sign in, sign up, etc.) 3. Auth Core Engine — The central logic that orchestrates authentication flows 4. Plugins — Optional modules that extend functionality (2FA, passkeys, etc.) 5. Database Adapter — Abstraction layer for your database of choice Key Concepts Auth Instance The auth instance is the central object that configures your authentication system. It's created with betterAuth() and holds all configuration, plugins, and database connections. Sessions Sessions represent an authenticated user's state. Better Auth uses secure, encrypted cookies to manage sessions automatically. Sessions can be configured with custom expiry times, refresh tokens, and more. Accounts An account links a user to an authentication method. A single user can have multiple accounts (e.g., email + Google + GitHub), all linked to the same user profile. Verification Verification tokens are used for email verification, password resets, and other flows that require proving ownership of an email address. Deep Dives - Session Management — How sessions work, token rotation, and security - Database Schema — Tables, relationships, and migrations --- ## Database URL: /docs/concepts/database Database schema, adapters, and automatic migrations. Database Better Auth uses your existing database — no proprietary backend required. It supports PostgreSQL, MySQL, SQLite, and MongoDB through built-in adapters. Supported Databases | Database | Adapter | ORM Support | | ---------- | ------------ | ------------------------------- | | PostgreSQL | postgresql | Prisma, Drizzle, raw SQL | | MySQL | mysql | Prisma, Drizzle, raw SQL | | SQLite | sqlite | Prisma, Drizzle, better-sqlite3 | | MongoDB | mongodb | Mongoose | Configuration Direct Connection With Prisma With Drizzle Schema Better Auth creates and manages these tables automatically: user | Column | Type | Description | | --------------- | ---------- | -------------------------- | | id | string | Primary key | | name | string | User's display name | | email | string | Unique email address | | emailVerified | boolean | Whether email is verified | | image | string? | Profile image URL | | createdAt | datetime | Account creation timestamp | | updatedAt | datetime | Last update timestamp | session | Column | Type | Description | | ----------- | ---------- | ------------------------ | | id | string | Primary key | | userId | string | Foreign key → user | | token | string | Session token (hashed) | | expiresAt | datetime | When the session expires | | ipAddress | string? | Client IP address | | userAgent | string? | Client user agent | account | Column | Type | Description | | -------------- | --------- | ------------------------------ | | id | string | Primary key | | userId | string | Foreign key → user | | providerId | string | Auth provider (e.g., "google") | | accountId | string | Provider-specific user ID | | accessToken | string? | OAuth access token | | refreshToken | string? | OAuth refresh token | verification | Column | Type | Description | | ------------ | ---------- | ----------------------------- | | id | string | Primary key | | identifier | string | What's being verified (email) | | value | string | Verification token | | expiresAt | datetime | Token expiry | Migrations Automatic Migrations Better Auth can automatically create and update tables: Generate Migration Files If you prefer to review migrations before applying: This creates SQL files you can review and apply manually. When using Prisma, run npx @better-auth/cli generate --prisma to generate Prisma schema additions instead of raw SQL. Custom Fields You can extend the default schema with custom fields: These fields are automatically added to the user table and included in the session user object. --- ## Session Management URL: /docs/concepts/session-management How sessions work in Better Auth — creation, validation, refresh, and security. Session Management Sessions are the backbone of authentication. They represent an authenticated user's state and determine what resources they can access. How Sessions Work When a user signs in, Better Auth: 1. Validates credentials — Checks email/password or verifies the social provider token 2. Creates a session — Generates a unique session ID and stores it in the database 3. Sets a cookie — Sends a secure, HttpOnly cookie to the client with the session token 4. Returns user data — Sends the user object and session details back to the client Session Configuration Configure session behavior in your auth instance: Configuration Options | Option | Type | Default | Description | | --------------------- | --------- | -------- | -------------------------------------- | | expiresIn | number | 604800 | Session duration in seconds (7 days) | | updateAge | number | 86400 | How often to refresh the session (24h) | | cookieCache.enabled | boolean | false | Enable client-side session caching | | cookieCache.maxAge | number | 300 | Cache duration in seconds | Retrieving Sessions Server-Side Client-Side Session Security Better Auth implements several security measures: - HttpOnly cookies — Session tokens are not accessible via JavaScript - Secure flag — Cookies are only sent over HTTPS in production - SameSite — Prevents CSRF attacks by restricting cross-origin cookies - Token rotation — Sessions are periodically refreshed with new tokens - IP binding — Optionally bind sessions to the originating IP address Always use HTTPS in production. Better Auth automatically sets the Secure cookie flag when NODE_ENV=production. Revoking Sessions Revoke Current Session Revoke All Sessions Revoke Specific Session Multi-Session Support Better Auth supports multiple concurrent sessions per user (e.g., different devices): Users can view and manage their active sessions: --- ## Create Content URL: /docs/create-content Write and format documentation content. Create Content Learn how to write rich, interactive documentation content using MDX. MDX Format Our framework uses MDX — Markdown with JSX support. Write standard Markdown with the ability to embed React components. Content Features - Rich text formatting with Markdown syntax - Code blocks with syntax highlighting - Images and embeds with automatic optimization - Interactive components with React/JSX - Math equations with LaTeX support - Diagrams with Mermaid Writing Tips 1. Keep paragraphs short and scannable 2. Use headings to create clear hierarchy 3. Include code examples for technical content 4. Add visual aids like images and diagrams --- ## Code Blocks URL: /docs/create-content/code-blocks Syntax highlighting and code block features. Code Blocks Display beautifully highlighted code in your documentation. Basic Code Block javascript function greet(name) { return Hello, ${name}!; } Supported Languages Code blocks support 100+ programming languages including: - JavaScript / TypeScript - Python - Go - Rust - Ruby - PHP - And many more Line Highlighting Highlight specific lines to draw attention: tsx {3-5} function App() { return ( Hello World ); } File Names Add a filename to your code block: tsx title="app/page.tsx" return Hello; } Code Groups Group related code blocks into tabs with the Mintlify-style syntax. The tab label can come from a bare filename after the language, title, or filename. CodeGroup is built in, so you do not need to import it or register it in docs.config.ts. The authoring syntax is just regular fenced code inside the group: bash npm npm install better-auth bash pnpm pnpm add better-auth ts title="auth.ts" emailAndPassword: { enabled: true, }, }); Agent Metadata Code fences can include extra metadata for agents and MCP tools. The rendered code block keeps the same visual treatment; the metadata is only parsed from the raw markdown and MCP source. ts title="docs.config.ts" framework="nextjs" packageManager="pnpm" runnable entry: "docs", }); Agents reading /docs/.md see the metadata directly on the code fence. MCP clients can call getcodeexamples to receive the same example as structured JSON: Use runnable only when the snippet is complete enough to copy into the named file or terminal. Line Numbers Enable line numbers for longer code blocks: tsx showLineNumbers const a = 1; const b = 2; const c = a + b; console.log(c); --- ## Format Text URL: /docs/create-content/format-text Text formatting options in MDX documentation. Format Text MDX supports all standard Markdown formatting plus JSX extensions. Basic Formatting Headings Use # symbols to create heading hierarchy: Lists Unordered Lists Ordered Lists Blockquotes Tables --- ## Images & Embeds URL: /docs/create-content/images-embeds Add images, videos, and embedded content to your docs. Images & Embeds Enrich your documentation with visual content. Images Standard Markdown With Custom Sizing Videos Embed videos from YouTube or other platforms: Callouts Use callouts to highlight important information: Cards Link to related content with cards: Tabs Show content in tabs: --- ## Customize URL: /docs/customize Customize the look and feel of your documentation. Customize Make your documentation site uniquely yours with themes, fonts, and custom components. Theming Choose from built-in themes or create your own: Available Themes Nine built-in themes: | Theme | Description | | -------------- | ---------------------------------------------- | | fumadocs | Default theme with clean design | | darksharp | All-black, sharp corners | | pixel-border | Refined dark UI inspired by better-auth.com | | colorful | Fumadocs-style neutral with description support| | greentree | Green-accented Mintlify-inspired theme | | darkbold | Monochrome Vercel-inspired theme | | shiny | Glossy modern theme | | hardline | Hard-edge high-contrast interface | | concrete | Brutalist poster-style interface with loud depth | Quick Customization Override any theme value: --- ## Custom 404 Page URL: /docs/customize/custom-404 Customize the 404 error page for your documentation. Custom 404 Page Create a custom 404 page for when users navigate to non-existent documentation pages. Create the Page Add a not-found.tsx file in your docs directory: Best Practices 1. Include a search bar to help users find what they're looking for 2. Link back to the docs home page 3. Show suggested pages based on the URL 4. Keep the design consistent with your docs theme --- ## Custom Domain URL: /docs/customize/custom-domain Connect your own domain to your documentation site. Set up a custom domain so your docs are served from your own URL (e.g., docs.yoursite.com). DNS Configuration Add a CNAME record pointing to your deployment: Verifying Ownership After adding the DNS record, verify ownership in your dashboard: 1. Navigate to Settings → Domains 2. Click Add Domain 3. Enter your custom domain 4. Wait for DNS propagation (usually under 5 minutes) SSL Certificates SSL certificates are provisioned automatically. No manual configuration is needed. Subpath Routing You can also serve docs from a subpath like yoursite.com/docs: --- ## Custom Scripts URL: /docs/customize/custom-scripts Add custom scripts and analytics to your docs. Custom Scripts Add analytics, tracking, or other custom scripts to your documentation. Analytics Google Analytics Add to your layout.tsx: Plausible Custom Head Tags Add meta tags or link elements in your layout: --- ## Fonts URL: /docs/customize/fonts Configure custom fonts for your documentation. Fonts Customize the typography of your documentation with custom fonts. Font Configuration Using Google Fonts Install and configure fonts in your layout.tsx: Font Size Scale | Element | Default Size | Weight | | ------- | ------------ | ------ | | h1 | 2.25rem | 700 | | h2 | 1.5rem | 600 | | h3 | 1.25rem | 600 | | body | 0.975rem | 400 | | small | 0.875rem | 400 | --- ## React URL: /docs/customize/react-components Add custom React components to your MDX pages. Custom React Components Extend your documentation with interactive React components. Registering Components Add components in your docs.config.ts: Using in MDX Once registered, use them directly in your MDX files: Built-in Components | Component | Description | | ----------- | ------------------------------ | | Callout | Highlighted information blocks | | Card | Content cards with links | | Steps | Numbered step-by-step guides | | Tabs | Tabbed content sections | | Accordion | Collapsible content sections | Component Variants --- ## Themes URL: /docs/customize/themes Choose and configure documentation themes. Themes Themes control the visual appearance of your documentation site. Applying a Theme Cross-Framework Theme Parity All built-in themes, including concrete, are available across Next.js, TanStack Start, SvelteKit, Astro, and Nuxt. Theme Options Each theme accepts an options object: Creating a Custom Theme Color Tokens | Token | Description | | ----------------- | ----------------------- | | primary | Primary brand color | | background | Page background | | foreground | Main text color | | muted | Muted background | | mutedForeground | Muted text | | border | Border color | | accent | Accent/hover background | --- ## Get Started URL: /docs/getting-started Build your first authentication flow with Better Auth. Get Started This guide walks you through building a complete sign-up and sign-in flow using Better Auth. Create the Auth Client First, create a client-side auth helper: Sign Up Create a sign-up form that calls the auth client: Sign In After registration, users can sign in: Get Current Session Check the current user's session: Sign Out Next Steps - Learn about Session Management - Set up a Database --- ## Agent-Ready Docs URL: /docs/getting-started/agent-ready-docs A single docs page that gives humans the full story and agents a focused sibling markdown guide. Agent-Ready Docs This page is intentionally written for human readers. It explains how the Next example app serves a single docs topic in two different forms: - /docs/getting-started/agent-ready-docs for human HTML - /docs/getting-started/agent-ready-docs.md for the page's direct agent.md - /docs/getting-started/agent-ready-docs with Signature-Agent for automatic markdown Because this folder includes a sibling agent.md, the .md route returns that file. For pages without agent.md, the same .md route and header-based markdown response fall back to the normal page markdown. What To Open 1. Open /docs/getting-started/agent-ready-docs in the browser to see the full narrative. 2. Open /docs/getting-started/agent-ready-docs.md to see the focused agent payload. 3. Request /docs/getting-started/agent-ready-docs with Signature-Agent to get the same focused payload from the canonical URL. 4. Use your own prompt cases to compare the human page output and the markdown agent payload. 5. Compare how much broader explanation humans get versus how much narrower implementation detail an agent gets. Why It Matters This is the simplest version of the pattern you wanted: - one folder - one page.mdx - one agent.md - two audience-specific experiences from the same slug Feature Goal The example app exposes two ways to read the same docs topic: - /docs/ for human HTML pages - /docs/.md for machine-readable markdown - /docs/ with Signature-Agent for agents that read canonical URLs When a page folder has an agent.md, the .md route and Signature-Agent response should return that file. When it does not, both markdown entry points should fall back to the normal page markdown. That fallback comes from the same docs source lookup used by the shared page reader, so pages without agent.md do not need any extra configuration. Files Involved The key files for this flow are: Zero-Config Layer The public .md URL now comes from withDocs() itself. Apps do not need to add their own rewrites or a custom markdown catch-all route. Built-In Markdown Route withDocs() wires the public .md URLs into the existing /api/docs handler. The public rewrite lands on /api/docs with format=markdown, so the shared docs API accepts both direct markdown queries and rewritten page URLs like /docs/getting-started/agent-ready-docs.md: Signature-Agent Auto-Rewrite Some agents fetch the canonical page URL and identify themselves with Signature-Agent instead of sending Accept: text/markdown. withDocs() handles that case automatically: the normal HTML URL continues to work for browsers, while requests with the header are rewritten to the existing /api/docs handler with format=markdown. No docs config flag is required. The header only changes docs page responses under the configured entry route, so unrelated pages are not hijacked. No extra API wrapper is generated; the existing app/api/docs/route.ts remains the single docs API entry point. MCP Route The example app also exposes the standard MCP surface: When agent.md exists, the .md route returns that file. MCP remains available for tool-based access and parity checks, but the HTTP .md route is the simple public contract. MCP Code Examples The MCP server also exposes getcodeexamples. It scans fenced code blocks from the raw markdown source and returns parsed metadata without changing the rendered code block UI. Use metadata on examples that agents should treat as implementation-ready: ts title="docs.config.ts" framework="nextjs" packageManager="pnpm" runnable entry: "docs", }); An MCP client can request only matching examples: The getcodeexamples response is JSON, so agents do not need to scrape rendered HTML: The MCP server also exposes list_docs for structured discovery before reading page bodies: The response includes matching page summaries plus a section tree: The MCP server also exposes getconfigschema for agents that need to edit docs.config.ts without guessing option names or defaults: Use query instead of option when the agent only knows the feature area, such as llms or page actions. A filtered getconfigschema response includes the matching option metadata: Docs Config The example app does not need any MCP flag. withDocs() picks up the default MCP surface automatically, so the markdown route and MCP can both be exercised without extra config: Folder Convention For this exact showcase, the folder is intentionally minimal: That is the whole pattern. Request Flow When a request comes in for /docs/getting-started/agent-ready-docs.md, withDocs() handles the rewrite automatically into the existing /api/docs handler. The shared docs API accepts either the explicit format=markdown&path=... query produced by the rewrite or a direct .md pathname in adapters that pass the public URL through, then resolves the requested slug and checks whether the page has agentRawContent. When a request comes in for /docs/getting-started/agent-ready-docs with Signature-Agent, withDocs() rewrites it into the existing /api/docs handler with format=markdown and the current docs slug as path. The same generated app/api/docs/route.ts handles search, markdown, llms.txt, skill, sitemap, feedback, and agent discovery formats. Because this page has a sibling agent.md, the response becomes the raw contents of that file. If another page does not have agent.md, the same route falls back to the normal page markdown. Useful Commands For MCP parity checks: Gotchas - In the Next example, contentDir should default to app/${entry} when the config does not set it explicitly. - The .md route is automatic in Next when you use withDocs(). - Signature-Agent is automatic in Next when you use withDocs() and does not require a docs.config option. - agent.md should stay hidden from normal docs discovery and sidebar generation. - When agent.md exists, it overrides the normal markdown for that slug. Why This Page Exists This page is intentionally richer and more explanatory than the agent override. It is meant to show that you can keep all the human context you want in page.mdx` while still serving a tight implementation-oriented document to agents from the exact same folder. --- ## AI-Native URL: /docs/getting-started/ai-native Configure AI-powered search and chat for your documentation. AI-Native Features Our framework includes built-in AI capabilities that make your docs smarter. Enable AI Search Add the AI configuration to your docs.config.ts: AI Modes | Mode | Description | | ---------- | ----------------------------------------- | | search | Integrated into the Cmd+K search dialog | | floating | Floating chat widget with slide-out panel | Suggested Questions Pre-populate your AI chat with common questions: Custom Loading States You can customize the loading indicator variant: Available variants: "shimmer-dots" (default), "circular", "dots", "typing", "wave", "bars", "pulse", "pulse-dot", "terminal", "text-blink", "text-shimmer", "loading-dots". --- ## Migration Guide URL: /docs/getting-started/migration-guide Migrate from other documentation frameworks. Migration Guide Moving from another documentation framework? This guide covers the key differences and migration steps. From Docusaurus 1. Content Format: Both use MDX, so your content files can be reused with minimal changes. 2. Configuration: Replace docusaurus.config.js with docs.config.ts. 3. Sidebar: Sidebars are generated automatically from the file system. From Nextra 1. File Structure: Similar file-based routing approach. 2. Theme: Replace Nextra's theme configuration with our theme system. 3. MDX Components: Custom components can be mapped in the config. From VitePress 1. Runtime: VitePress uses Vite; we use Next.js. 2. Markdown: VitePress uses standard Markdown; we use MDX. 3. Configuration: Replace .vitepress/config.ts with docs.config.ts. Common Migration Steps --- ## Quickstart URL: /docs/getting-started/quickstart Get your documentation site running in under 5 minutes. Quickstart Follow these steps to create your first documentation site. Create a New Project Start the Development Server Your docs site will be available at http://localhost:3000/docs. Project Structure Add Your First Page Create a new file at app/docs/my-page/page.mdx: Next Steps - Configure your sidebar navigation - Add custom themes - Set up AI-powered search --- ## Installation URL: /docs/installation Install and configure Better Auth in your project. Installation Getting started with Better Auth takes just a few minutes. This guide walks you through installing the package, setting up your database, and creating your first auth instance. Prerequisites Before you begin, make sure you have: - Node.js 18 or later - A database — PostgreSQL, MySQL, SQLite, or MongoDB - A package manager — npm, yarn, pnpm, or bun Install the Package Set Up Environment Variables Create a .env file in your project root: Note: Never commit your .env file to version control. Add it to your .gitignore. Create Auth Instance Create an auth.ts file in your project: Verify Installation Start your development server and visit http://localhost:3000/api/auth/ok. You should see a JSON response confirming the auth server is running: Next Steps - Follow the Get Started guide - Learn about Session Management --- ## Integrations URL: /docs/integrations Framework integrations — Next.js, Nuxt, SvelteKit, Astro, and more. Integrations Better Auth is framework-agnostic but provides first-class integrations for popular frameworks. Supported Frameworks | Framework | Handler | Client SDK | | ---------------- | -------------------- | ------------------------------ | | Next.js | toNextJsHandler | better-auth/react | | Nuxt | toH3Handler | better-auth/vue | | SvelteKit | toSvelteKitHandler | better-auth/svelte | | Astro | Built-in support | better-auth/react or vanilla | | Express | toNodeHandler | Any client SDK | | Hono | toHonoHandler | Any client SDK | | Elysia (Bun) | toElysiaHandler | Any client SDK | | Fastify | toNodeHandler | Any client SDK | Next.js API Route Middleware Server Components Nuxt Server Plugin Composable Express / Node.js Hono SvelteKit Server Hook Page --- ## Organize URL: /docs/organize Structure and organize your documentation content. Organize Learn how to structure your documentation for the best reader experience. File-Based Routing Our framework uses file-based routing. Each page.mdx file in the app/docs/ directory becomes a documentation page. Directory Structure Organize pages into folders to create logical groupings: Sidebar Generation The sidebar is automatically generated from your file structure. Folders with child pages become expandable sections. --- ## Agent Pages URL: /docs/organize/agent-pages Keep a human page and an optional agent-only companion sidecar in the same folder. Agent Pages Use a normal page.mdx for readers and add a sibling agent.md only when a page needs agent-specific instructions. Folder Structure Human Behavior Readers still visit the regular page route and only see the human documentation content. Agent Behavior Agents can open /docs/organize/agent-pages.md or keep using MCP read_page("/docs/organize/agent-pages"). When agent.md exists, the markdown route and MCP response return that page-local markdown instead of the normal page content. If agent.md is missing, both fall back to the normal page content. When To Use It - Implementation checklists - Exact commands - Edge cases that matter more to agents than readers - Repo-specific constraints you do not want in the public prose --- ## Exclude Files URL: /docs/organize/exclude-files Exclude specific files or directories from documentation. Exclude Files Control which files are included in your documentation build. Ignoring Directories Files and directories starting with _ or . are automatically ignored: Excluding from Search To keep a page visible but exclude it from search results: Excluding from Sitemap Best Practices 1. Use _ prefix for work-in-progress content 2. Use hidden frontmatter for pages you want accessible but not in the sidebar 3. Use searchable: false for pages that shouldn't appear in search --- ## Global Settings URL: /docs/organize/global-settings Configure global settings for your documentation site. Global Settings Global settings are configured in docs.config.ts and apply to every page in your documentation. Configuration File Available Options | Option | Type | Default | Description | | ------------- | -------- | ------------------- | ------------------------------- | | entry | string | "docs" | Directory containing docs pages | | metadata | object | — | SEO metadata configuration | | themeToggle | object | { enabled: true } | Dark/light mode toggle | | nav | object | — | Navigation title and URL | | sidebar | object | — | Sidebar configuration | --- ## Hidden Pages URL: /docs/organize/hidden-pages Hide pages from the sidebar while keeping them accessible. Hidden Pages Sometimes you need pages that are accessible via URL but hidden from the sidebar navigation. Using Frontmatter Add hidden: true to your page's frontmatter: Use Cases - Draft content: Pages still being written - Internal pages: Content for specific audiences - Redirect targets: Pages that only serve as redirect destinations - API callbacks: Documentation for webhook endpoints Accessing Hidden Pages Hidden pages are still accessible via their URL. You can link to them from other pages: --- ## Navigation URL: /docs/organize/navigation Configure navigation and sidebar ordering. Navigation Control how pages appear in the sidebar and how they're ordered. Sidebar Ordering By default, pages are sorted alphabetically. You can change this: Alphabetical (Default) Numeric Ordering Use the order frontmatter field: Custom Ordering Specify exact page order: Breadcrumbs Enable breadcrumb navigation: --- ## Pages URL: /docs/organize/pages Configure page metadata, titles, and frontmatter properties. Pages Every documentation page is an MDX file with frontmatter metadata. Frontmatter Available Properties | Property | Type | Description | | ------------- | -------- | ------------------------------------------- | | title | string | Page title displayed in sidebar and heading | | description | string | Page description for SEO and previews | | icon | string | Icon key from the icons registry | | order | number | Sort order when using numeric ordering | Page Descriptions Descriptions appear below the page title and in search results: Icons Reference icons from your docs.config.ts icons registry: Then use them in frontmatter: --- ## Overview URL: /docs/overview Human-facing overview page for the docs example. Overview This page is the normal human-facing documentation page. Readers should see this content at /docs/overview. What It Shows - A standard page.mdx page for humans - A sibling agent.md file for agent-specific markdown reads - A clean split between reader content and agent-specific instructions Testing The Split - Open /docs/overview in the browser to see the human page - Open /docs/overview.md to get the page-local agent markdown - Use MCP read_page("/docs/overview") to read the same agent override through MCP The two should be different when agent.md exists. --- ## Plugins URL: /docs/plugins Extend Better Auth with powerful plugins — 2FA, organizations, passkeys, and more. Plugins Better Auth's plugin system lets you add powerful features without bloating the core. Each plugin is self-contained with its own database schema, API endpoints, and client-side utilities. How Plugins Work Plugins hook into Better Auth's lifecycle: Each plugin can: - Add API endpoints — e.g., /api/auth/two-factor/verify - Extend the database schema — e.g., add an organization table - Add client-side utilities — e.g., authClient.twoFactor.verify() - Hook into auth events — e.g., run custom logic after sign-in Available Plugins Authentication | Plugin | Description | | -------------------------------------- | -------------------------------------------- | | Two Factor | TOTP, SMS, and backup codes | | Passkey | WebAuthn / FIDO2 passwordless authentication | | Magic Link | Passwordless email authentication | | Phone Number | SMS-based authentication | | Anonymous | Allow anonymous/guest users | Authorization & Access Control | Plugin | Description | | -------------------------------------------- | ------------------------------------ | | Organizations | Multi-tenant organization management | | Admin | Admin dashboard and user management | | RBAC | Role-based access control | Enterprise | Plugin | Description | | ------------- | --------------------------------------------- | | OIDC Provider | Turn your app into an OpenID Connect provider | | SAML | Enterprise SSO with SAML 2.0 | | SCIM | Automated user provisioning | Utilities | Plugin | Description | | ---------- | ---------------------------------- | | Rate Limit | Advanced rate limiting rules | | Captcha | Bot protection with CAPTCHA | | Webhook | Real-time auth event notifications | Client-Side Plugin Setup Plugins that add client-side features need to be registered on the auth client too: Creating Custom Plugins You can build your own plugins: Deep Dives - Two Factor Authentication — TOTP setup and verification - Organizations — Multi-tenant team management --- ## Organizations URL: /docs/plugins/organizations Multi-tenant organization management with roles and invitations. Organizations The organizations plugin adds multi-tenant support to your app. Users can create organizations, invite members, assign roles, and manage teams. Setup Client Setup Creating an Organization Inviting Members Accept an Invitation Managing Members List Members Update Member Role Remove a Member Active Organization Users can be part of multiple organizations. Set the active one: Server-Side Usage Check Organization Membership Database Schema The plugin adds these tables: | Table | Description | | -------------- | ------------------------------------------- | | organization | Organization details (name, slug, metadata) | | member | User-organization relationship with roles | | invitation | Pending invitations | Permissions Define custom permissions per role: Check permissions: --- ## Two Factor Authentication URL: /docs/plugins/two-factor Add TOTP-based two factor authentication with backup codes. Two Factor Authentication Two factor authentication (2FA) adds an extra layer of security by requiring users to provide a second form of verification beyond their password. Installation The 2FA plugin is included in the Better Auth package: Client Setup Enabling 2FA for a User Step 1: Generate TOTP Secret Step 2: Show QR Code Step 3: Verify Initial Code Sign-In with 2FA When 2FA is enabled, sign-in becomes a two-step process: Backup Codes Backup codes allow users to sign in if they lose access to their authenticator app: Regenerate Backup Codes Always remind users to save their backup codes in a secure location. They cannot be retrieved after the initial display. Disabling 2FA Configuration Reference | Option | Type | Default | Description | | --------------------- | --------- | -------- | ----------------------------------- | | issuer | string | required | Name shown in authenticator apps | | period | number | 30 | TOTP code rotation period (seconds) | | digits | number | 6 | Number of digits in TOTP code | | algorithm | string | "SHA1" | Hash algorithm | | backupCodes.enabled | boolean | true | Enable backup codes | | backupCodes.count | number | 10 | Number of backup codes | | backupCodes.length | number | 8 | Length of each backup code | --- ## Quickstart URL: /docs/quickstart Get up and running in minutes Quickstart This guide walks you through creating your first documentation page. Creating a Page Create a new folder under app/docs/ with a page.mdx file: Then create app/docs/my-page/page.mdx: Your page is now available at /docs/my-page. Using Components Callouts This is an informational callout. Use it for tips and notes. This is a warning callout. Use it for important caveats. Code Blocks Code blocks are automatically syntax-highlighted: Customizing the Theme Edit docs.config.ts to change colors, typography, and component defaults: Deploying Build your docs for production: Deploy to Vercel, Netlify, or any Node.js hosting platform. --- ## API Reference: OpenAPI mode is now the default URL: /docs/changelogs/2026-04-15 The Next example now ships with the faster OpenAPI experience, plus a tighter docs/API switcher. What shipped The Next example now uses the Fumadocs OpenAPI renderer by default, which keeps the API reference inside the same overall docs experience instead of dropping into a separate shell. Why it matters - Navigation between documentation and API reference feels much faster. - The shared theme carries through more cleanly. - Route generation is simpler for new projects. Small improvements - The docs/API switcher stays in the familiar dropdown style. - Remote specs continue to work for quick demos. - Generated routes are cleaner for new scaffolds. --- ## Colorful theme cleanup across docs and API routes URL: /docs/changelogs/2026-04-03 We tightened the theme handoff so the colorful preset keeps its own identity when moving between docs and API reference. What changed We cleaned up a handful of styling collisions that made the colorful preset feel inconsistent across different parts of the example app. Highlights - Sidebar visuals now stay closer to the intended colorful look. - Shared API reference styles no longer stomp the active docs palette. - Theme switching feels more predictable when moving around the app. Why we did it Theme presets only feel real when they stay coherent everywhere, not just on the main docs pages. --- ## Cloud page motion pass URL: /docs/changelogs/2026-03-18 The cloud landing page picked up smoother looping motion, better path-based SVG behavior, and more stable theme controls. Update We spent time polishing the cloud marketing page so the motion feels more intentional and less like placeholder animation. Included - looping layered-stack motion - improved text shuffle timing - more precise SVG path animation work - theme-toggle consistency fixes across the docs footer and cloud page Outcome The page feels calmer, more deliberate, and much closer to a product surface instead of a rough prototype. ---