Welcome to Better Auth
Relevant source files
The following files were used as context for generating this wiki page:- README.md
- CONTRIBUTING.md
- demo/nextjs/README.md
- packages/cli/README.md
- packages/cli/src/commands/init.ts
- packages/cli/src/generators/auth-config.ts
- packages/cli/src/commands/info.ts
- packages/better-auth/README.md
- packages/better-auth/package.json
- packages/better-auth/src/context/create-context.test.ts
- packages/expo/README.md
- demo/oidc-client/src/pages/Home.tsx
- CODE_OF_CONDUCT.md
- packages/cli/test/info.test.ts
- demo/nextjs/package.json
Better Auth is a framework-agnostic authentication and authorization library for TypeScript. It provides a comprehensive set of features out-of-the-box and includes a plugin ecosystem that simplifies adding advanced functionalities with minimal code. The project's goal is to provide a more complete open-source solution for authentication in the TypeScript ecosystem, allowing developers to focus on their application's core logic instead of reinventing authentication.
The project is free, open-source, and licensed under the MIT License. Community contributions are encouraged, and there is a defined Code of Conduct to ensure a welcoming and safe environment.
Sources: README.md:20-25, CODE_OF_CONDUCT.md
Project Structure
Better Auth is a monorepo managed with pnpm. The structure is organized into several packages, each serving a specific purpose.
Sources: CONTRIBUTING.md:9-17
The following diagram illustrates the high-level structure of the monorepo:
Key Packages
| Package | Description | Source |
|---|---|---|
packages/better-auth | The core authentication library. | [CONTRIBUTING.md:11](https://github.com/better-auth/better-auth/blob/HEAD/CONTRIBUTING.md#L11) |
packages/cli | Command-line interface (CLI) tools for project initialization and schema management. | [CONTRIBUTING.md:12](https://github.com/better-auth/better-auth/blob/HEAD/CONTRIBUTING.md#L12) |
packages/core | Contains core types, utilities, and contexts used by other packages. | [packages/core/package.json](https://github.com/better-auth/better-auth/blob/HEAD/packages/core/package.json) |
packages/expo | Provides integration with Expo for React Native applications. | [CONTRIBUTING.md:13](https://github.com/better-auth/better-auth/blob/HEAD/CONTRIBUTING.md#L13) |
packages/stripe | A plugin for integrating with Stripe for payments and subscriptions. | [CONTRIBUTING.md:14](https://github.com/better-auth/better-auth/blob/HEAD/CONTRIBUTING.md#L14) |
packages/sso | A plugin that adds SAML and OIDC support for Single Sign-On. | [CONTRIBUTING.md:15](https://github.com/better-auth/better-auth/blob/HEAD/CONTRIBUTING.md#L15) |
demo/ | Contains demo applications, such as a Next.js app, showcasing features. | [CONTRIBUTING.md:17](https://github.com/better-auth/better-auth/blob/HEAD/CONTRIBUTING.md#L17) |
Core Features
Better Auth comes with a wide range of features available out of the box, as demonstrated in the Next.js demo application.
| Feature | Description |
|---|---|
| Email & Password | Simple and secure authentication using email and password. |
| Organization / Teams | Manage users within organizations or teams. |
| Passkeys | Passwordless login using modern authentication standards. |
| Multi-Factor Authentication (MFA) | Add an extra layer of security with 2FA. |
| Password Reset | Allows users to reset their forgotten passwords. |
| Email Verification | Ensures users verify their email addresses. |
| Roles & Permissions | Define and manage user roles and permissions. |
| Rate Limiting | Protects the application from abuse with smart request limits. |
| Session Management | Handles user sessions seamlessly. |
| Stripe Plugin | Integrates Stripe for customer management and subscriptions. |
| OIDC Provider | Can act as an OpenID Connect provider for SSO. |
Sources: demo/nextjs/README.md:46-57, demo/oidc-client/src/pages/Home.tsx:8-20
Getting Started
To start using Better Auth, you first need to install the main package.
pnpm install better-auth
Sources: packages/better-auth/README.md:25-27
For local development on the Better Auth project itself, follow these steps:
- Fork and clone the repository.
- Install
pnpmglobally. - Run
pnpm installto install all dependencies across the monorepo. - Run
pnpm buildto build all the packages.
Sources: CONTRIBUTING.md:26-61
Command-Line Interface (CLI)
The @better-auth/cli package provides essential tools for initializing and managing a Better Auth project.
Sources: packages/cli/README.md:3-5
CLI Commands
| Command | Description |
|---|---|
init | Initializes Better Auth in your project, creating configuration files and setting up dependencies. |
generate | Generates the required database schema for your chosen adapter (e.g., Prisma, Drizzle, or SQL). |
migrate | Applies the schema directly to your database (for the built-in Kysely adapter). |
secret | Generates a secure secret key for your Better Auth instance. |
info | Displays system, framework, database, and Better Auth configuration information for debugging. |
Sources: packages/cli/README.md:8-29, packages/cli/src/commands/info.ts:352-356
The init Command Workflow
The init command is an interactive wizard that guides you through setting up Better Auth. It performs several checks and configurations.
The diagram below shows the general flow of the init command.
Configuration
Configuration is primarily handled in an auth.ts file and through environment variables.
Core Configuration (auth.ts)
The init CLI command helps create an auth.ts file. This is where you define your authentication strategy, enable plugins, and connect to a database.
A minimal configuration looks like this:
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
appName: "my-app",
plugins: [],
});
Sources: packages/cli/src/commands/init.ts:228-236
Environment Variables
Several key settings are configured via environment variables. The CLI will prompt to add these to your .env file during initialization.
| Variable | Description |
|---|---|
BETTER_AUTH_SECRET | A long, random string used for signing tokens and encrypting data. This is a critical security setting. |
BETTER_AUTH_URL | The base URL of your application. Used for constructing callback URLs. Defaults to http://localhost:3000. |
DATABASE_URL | The connection string for your database, used by many database adapters. |
Sources: packages/cli/src/commands/init.ts:723-736, 899-902, packages/better-auth/src/context/create-context.test.ts:182-194
The configuration loading logic prioritizes settings in a specific order. For example, the secret is resolved as follows:
secretproperty inbetterAuthoptions.BETTER_AUTH_SECRETenvironment variable.AUTH_SECRETenvironment variable (as a fallback).
Sources: packages/better-auth/src/context/create-context.test.ts:182-214
Plugin System
Better Auth's functionality is highly extensible through a plugin system. Plugins can add new authentication methods, integrate with third-party services, or modify core behavior.
Supported Plugins
The CLI init command provides a list of available plugins to add during setup.
| Plugin ID | Description |
|---|---|
two-factor | Adds Two-Factor Authentication (2FA). |
username | Allows sign-in with a username in addition to email. |
passkey | Enables passwordless authentication with passkeys. |
magic-link | Implements passwordless login via email links. |
email-otp | Implements login/verification via One-Time Passcodes sent to email. |
generic-oauth | A generic provider for any OAuth2-compliant service. |
organization | Adds multi-tenancy support with teams/organizations. |
sso | Adds SAML and OIDC support for Single Sign-On. |
oidc | Configures the instance to act as an OIDC provider. |
next-cookies | Recommended plugin for Next.js projects to handle cookies. |
admin | Provides administrative roles and permissions. |
api-key | Adds support for API key authentication. |
bearer | Adds support for bearer token authentication. |
Sources: packages/cli/src/commands/init.ts:55-220
Plugins are added to the plugins array in your auth.ts configuration. The generateAuthConfig function in the CLI handles the code generation for adding these plugins.
Sources: packages/cli/src/generators/auth-config.ts:14-41
Database Support
Better Auth can work with or without a database. For stateful operations like storing user accounts and sessions, it supports multiple databases and ORMs through an adapter system.
Supported Databases & Adapters
The CLI can configure the following database options:
| Adapter Type | Supported Dialects |
|---|---|
| Kysely (built-in) | sqlite, mysql, mssql, postgres |
| Drizzle | drizzle:pg, drizzle:mysql, drizzle:sqlite |
| Prisma | prisma:postgresql, prisma:mysql, prisma:sqlite |
| MongoDB | mongodb |
Sources: packages/cli/src/commands/init.ts:28-44, packages/cli/src/generators/auth-config.ts:223-400
When you select a database during init, the CLI automatically adds the necessary adapter code and dependencies to your project. For example, for Prisma with PostgreSQL, it will generate:
import { prismaAdapter } from "better-auth/adapters/prisma";
import { PrismaClient } from "@prisma/client";
const client = new PrismaClient();
// ... inside betterAuth config
database: prismaAdapter(client, {
provider: "postgresql",
})
Sources: packages/cli/src/generators/auth-config.ts:327-353
Conclusion
Better Auth is a powerful and flexible authentication framework designed for the modern TypeScript ecosystem. Its framework-agnostic nature, rich plugin system, and comprehensive CLI tooling make it a strong choice for developers looking to implement robust authentication without being locked into a specific service or writing extensive boilerplate code. By providing out-of-the-box solutions for common and advanced authentication patterns, it allows teams to secure their applications efficiently and focus on building features.
Sources: README.md:20-25, packages/cli/README.md