Docs

Options

List of all the available options for configuring Better Auth. See Better Auth Options.

appName

The name of the application.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	appName: "My App",
})

baseURL

Base URL for Better Auth. This is typically the root URL where your application server is hosted.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	baseURL: "https://example.com",
})

If not explicitly set, the system will check for the environment variable process.env.BETTER_AUTH_URL. If not set, it will throw an error.

basePath

Base path for Better Auth. This is typically the path where the Better Auth routes are mounted.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	basePath: "/api/auth",
})

Default: /api/auth

secret

The secret used for encryption, signing, and hashing.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	secret: "your-secret-key",
})

By default, Better Auth will look for the following environment variables:

  • process.env.BETTER_AUTH_SECRET
  • process.env.AUTH_SECRET

If none of these environment variables are set, it will default to "better-auth-secret-123456789". In production, if it's not set, it will throw an error.

You can generate a good secret using the following command:

openssl rand -base64 32

database

Database configuration for Better Auth.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	database: {
		dialect: "postgres",
		type: "postgres",
		casing: "camel"
	},
})

Better Auth supports various database configurations including PostgreSQL, MySQL, and SQLite.

Read more about databases here.

secondaryStorage

Secondary storage configuration used to store session and rate limit data.

import { betterAuth } from "better-auth";
import { redisStorage } from "better-auth/storage";
 
export const auth = betterAuth({
	secondaryStorage: redisStorage({
		url: "redis://localhost:6379"
	}),
})

Read more about secondary storage here.

emailVerification

Email verification configuration.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	emailVerification: {
		sendVerificationEmail: async ({ user, url, token }) => {
			// Send verification email to user
		},
		sendOnSignUp: true,
		autoSignInAfterVerification: true,
		expiresIn: 3600 // 1 hour
	},
})
  • sendVerificationEmail: Function to send verification email
  • sendOnSignUp: Send verification email automatically after sign up (default: false)
  • autoSignInAfterVerification: Auto sign in the user after they verify their email
  • expiresIn: Number of seconds the verification token is valid for (default: 3600 seconds)

emailAndPassword

Email and password authentication configuration.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	emailAndPassword: {
		enabled: true,
		disableSignUp: false,
		requireEmailVerification: true,
		minPasswordLength: 8,
		maxPasswordLength: 128,
		autoSignIn: true,
		sendResetPassword: async ({ user, url, token }) => {
			// Send reset password email
		},
		resetPasswordTokenExpiresIn: 3600, // 1 hour
		password: {
			hash: async (password) => {
				// Custom password hashing
				return hashedPassword;
			},
			verify: async ({ hash, password }) => {
				// Custom password verification
				return isValid;
			}
		}
	},
})
  • enabled: Enable email and password authentication (default: false)
  • disableSignUp: Disable email and password sign up (default: false)
  • requireEmailVerification: Require email verification before a session can be created
  • minPasswordLength: Minimum password length (default: 8)
  • maxPasswordLength: Maximum password length (default: 128)
  • autoSignIn: Automatically sign in the user after sign up
  • sendResetPassword: Function to send reset password email
  • resetPasswordTokenExpiresIn: Number of seconds the reset password token is valid for (default: 3600 seconds)
  • password: Custom password hashing and verification functions

socialProviders

Configure social login providers.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	socialProviders: {
		google: {
			clientId: "your-client-id",
			clientSecret: "your-client-secret",
			redirectUri: "https://example.com/api/auth/callback/google"
		},
		github: {
			clientId: "your-client-id",
			clientSecret: "your-client-secret",
			redirectUri: "https://example.com/api/auth/callback/github"
		}
	},
})

plugins

List of Better Auth plugins.

import { betterAuth } from "better-auth";
import { emailOTP } from "better-auth/plugins";
 
export const auth = betterAuth({
	plugins: [
		emailOTP({
			sendVerificationOTP: async ({ email, otp, type }) => {
				// Send OTP to user's email
			}
		})
	],
})

user

User configuration options.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	user: {
		modelName: "users",
		fields: {
			email: "emailAddress",
			name: "fullName"
		},
		additionalFields: {
			customField: {
				type: "string",
				nullable: true
			}
		},
		changeEmail: {
			enabled: true,
			sendChangeEmailVerification: async ({ user, newEmail, url, token }) => {
				// Send change email verification
			}
		},
		deleteUser: {
			enabled: true,
			sendDeleteAccountVerification: async ({ user, url, token }) => {
				// Send delete account verification
			},
			beforeDelete: async (user) => {
				// Perform actions before user deletion
			},
			afterDelete: async (user) => {
				// Perform cleanup after user deletion
			}
		}
	},
})
  • modelName: The model name for the user (default: "user")
  • fields: Map fields to different column names
  • additionalFields: Additional fields for the user table
  • changeEmail: Configuration for changing email
  • deleteUser: Configuration for user deletion

session

Session configuration options.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	session: {
		modelName: "sessions",
		fields: {
			userId: "user_id"
		},
		expiresIn: 604800, // 7 days
		updateAge: 86400, // 1 day
		additionalFields: {
			customField: {
				type: "string",
				nullable: true
			}
		},
		storeSessionInDatabase: true,
		preserveSessionInDatabase: false,
		cookieCache: {
			enabled: true,
			maxAge: 300 // 5 minutes
		}
	},
})
  • modelName: The model name for the session (default: "session")
  • fields: Map fields to different column names
  • expiresIn: Expiration time for the session token in seconds (default: 604800 - 7 days)
  • updateAge: How often the session should be refreshed in seconds (default: 86400 - 1 day)
  • additionalFields: Additional fields for the session table
  • storeSessionInDatabase: Store session in database when secondary storage is provided (default: false)
  • preserveSessionInDatabase: Preserve session records in database when deleted from secondary storage (default: false)
  • cookieCache: Enable caching session in cookie

account

Account configuration options.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	account: {
		modelName: "accounts",
		fields: {
			userId: "user_id"
		},
		accountLinking: {
			enabled: true,
			trustedProviders: ["google", "github", "email-password"],
			allowDifferentEmails: false
		}
	},
})
  • modelName: The model name for the account
  • fields: Map fields to different column names
  • accountLinking: Configuration for account linking

verification

Verification configuration options.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	verification: {
		modelName: "verifications",
		fields: {
			userId: "user_id"
		},
		disableCleanup: false
	},
})
  • modelName: The model name for the verification table
  • fields: Map fields to different column names
  • disableCleanup: Disable cleaning up expired values when a verification value is fetched

advanced

Advanced configuration options.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	advanced: {
		ipAddress: {
			ipAddressHeaders: ["x-client-ip", "x-forwarded-for"],
			disableIpTracking: false
		},
		useSecureCookies: true,
		disableCSRFCheck: false,
		crossSubDomainCookies: {
			enabled: true,
			additionalCookies: ["custom_cookie"],
			domain: "example.com"
		},
		cookies: {
			session_token: {
				name: "custom_session_token",
				attributes: {
					httpOnly: true,
					secure: true
				}
			}
		},
		defaultCookieAttributes: {
			httpOnly: true,
			secure: true
		},
		cookiePrefix: "myapp",
		generateId: ((options: {
			model: LiteralUnion<Models, string>;
			size?: number;
		}) => {
			// Generate a unique ID for the model
			return "my-id";
		}) 
	},
})
  • ipAddress: IP address configuration for rate limiting and session tracking
  • useSecureCookies: Use secure cookies (default: false)
  • disableCSRFCheck: Disable trusted origins check (⚠️ security risk)
  • crossSubDomainCookies: Configure cookies to be shared across subdomains
  • cookies: Customize cookie names and attributes
  • defaultCookieAttributes: Default attributes for all cookies
  • cookiePrefix: Prefix for cookies
  • generateId: Function to generate a unique ID for a model

databaseHooks

Database lifecycle hooks for core operations.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	databaseHooks: {
		user: {
			create: {
				before: async (user) => {
					// Modify user data before creation
					return { data: { ...user, customField: "value" } };
				},
				after: async (user) => {
					// Perform actions after user creation
				}
			},
			update: {
				before: async (userData) => {
					// Modify user data before update
					return { data: { ...userData, updatedAt: new Date() } };
				},
				after: async (user) => {
					// Perform actions after user update
				}
			}
		},
		session: {
			// Session hooks
		},
		account: {
			// Account hooks
		},
		verification: {
			// Verification hooks
		}
	},
})

onAPIError

API error handling configuration.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	onAPIError: {
		throw: true,
		onError: (error, ctx) => {
			// Custom error handling
			console.error("Auth error:", error);
		},
		errorURL: "/auth/error"
	},
})
  • throw: Throw an error on API error (default: false)
  • onError: Custom error handler
  • errorURL: URL to redirect to on error (default: /api/auth/error)

hooks

Request lifecycle hooks.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	hooks: {
		before: async (request, ctx) => {
			// Execute before processing the request
		},
		after: async (request, response, ctx) => {
			// Execute after processing the request
		}
	},
})

disabledPaths

Disable specific auth paths.

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	disabledPaths: ["/api/auth/signup", "/api/auth/signin/email"],
})

On this page