# Better Auth Setup and Configuration

> Configure Better Auth for your SaaS application including core settings, database adapter, and security options.

*Canonical: https://makerkit.dev/docs/nextjs-prisma/better-auth/setup*

---

Configure [Better Auth](https://www.better-auth.com/) in one place - the `@kit/better-auth` package - and the entire kit inherits your auth settings.

This page is part of the [Authentication documentation](./overview).

Better Auth configuration lives in `packages/better-auth/src/auth.ts`. This file defines the Prisma database adapter, enabled plugins (MFA, organizations, OAuth), email handlers, and security settings. The client-side auth instance in `auth-client.ts` mirrors this configuration. A separate `config.ts` is the env-free schema-generation entrypoint used by `schema:generate` (see [Adding Plugins](./adding-plugins)). Edit these files to customize authentication behavior - everything else in the kit consumes auth through the `@kit/better-auth` package exports.

The Better Auth setup file (`auth.ts`) is the central configuration that initializes the auth instance with your database adapter, plugins, and security settings.

- **Modify setup when:** you need to add plugins, change session duration, customize email handlers, or switch database adapters.
- **Avoid modifying when:** you only need to enable/disable auth methods - use environment variables for that.

## File Structure

```
packages/better-auth/
└── src/
    ├── auth.ts                # Runtime server-side Better Auth instance
    ├── config.ts              # Env-free schema-generation entrypoint
    ├── auth.features.ts       # Build-time feature toggles
    ├── auth-client.ts         # Client-side auth instance
    └── plugins/
        ├── two-factor.ts      # MFA/TOTP configuration
        ├── social-providers.ts # OAuth providers
        ├── rate-limit.ts      # Rate limiting
        └── ...                # Other plugins
```

## Core Configuration

The `packages/better-auth/src/auth.ts` file defines:

- **Database Adapter**: [Prisma ORM](https://www.prisma.io/) connecting to PostgreSQL
- **Plugins**: MFA, organizations, OAuth providers, rate limiting
- **Email Handlers**: Password reset, email verification, invitations
- **Session Settings**: Token duration, cookie configuration
- **Security**: Secret key, allowed origins

## Required Environment Variables

```bash {% title="./.env.local" %}
# Required - generate with: openssl rand -base64 32
BETTER_AUTH_SECRET=your-32-character-or-longer-secret

# Database connection
DATABASE_URL=postgresql://user:password@localhost:5432/myapp

# Site URL for OAuth callbacks
NEXT_PUBLIC_SITE_URL=http://localhost:3000
```

## Database Adapter

The kit uses [Prisma ORM](https://www.prisma.io/docs) to connect to PostgreSQL. Prisma supports other databases (MySQL, SQLite, SQL Server) - change the provider in your schema if needed.

The auth tables (users, sessions, accounts, verifications) are defined in the Prisma schema at `packages/database/src/prisma/schema.prisma`.

## Common Pitfalls

- **Missing `BETTER_AUTH_SECRET`**: Auth won't work without this. Generate a secure secret with `openssl rand -base64 32`.
- **Secret too short**: Must be at least 32 characters for security.
- **Editing `auth.ts` when environment variables suffice**: Visibility toggles like email/password, magic links, passkeys, and OAuth provider buttons are controlled by env vars. Plugin wiring such as MFA still lives in `auth.ts`.
- **Forgetting to restart after env changes**: Next.js caches environment variables. Restart the dev server after changes.
- **Mismatched client/server plugins**: If you add a server plugin with client functionality, add the client plugin to `auth-client.ts` too.

{% faq
   title="Frequently Asked Questions"
   items=[
     {"question": "Where do I add a new Better Auth plugin?", "answer": "Create a file in packages/better-auth/src/plugins/, then import it into packages/better-auth/src/auth.ts and add it to the plugins array there."},
     {"question": "How do I change session duration?", "answer": "Modify the session configuration in auth.ts. Better Auth defaults to 7 days. See the Better Auth session documentation."},
     {"question": "Can I use MySQL instead of PostgreSQL?", "answer": "Yes. Change the Prisma provider in schema.prisma to mysql, update DATABASE_URL, and run migrations."},
     {"question": "Where are auth-related emails sent from?", "answer": "Email handlers in auth.ts use dynamic imports to load templates from @kit/email-templates. The actual sending uses your configured mailer (Resend, Nodemailer, etc.)."}
   ]
/%}

---

**Next:** [Auth Methods →](./auth-methods)
