### Complete Server-Side Configuration Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md A full example demonstrating the setup of the two-factor plugin for a server-side application, including TOTP, OTP, backup code, and session settings. ```typescript import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins"; import { sendEmail } from "./email"; export const auth = betterAuth({ appName: "My App", plugins: [ twoFactor({ // Display settings issuer: "My App", // TOTP settings totpOptions: { digits: 6, period: 30, }, // OTP settings otpOptions: { sendOTP: async ({ user, otp }) => { await sendEmail({ to: user.email, subject: "Your verification code", text: `Your code is: ${otp}`, }); }, period: 5, // 5 minutes digits: 6, allowedAttempts: 5, storeOTP: "encrypted", }, // Backup codes backupCodeOptions: { amount: 10, length: 10, storeBackupCodes: "encrypted", }, // Session settings twoFactorCookieMaxAge: 600, // 10 minutes trustDeviceMaxAge: 30 * 24 * 60 * 60, // 30 days }), ], }); ``` -------------------------------- ### Complete Better Auth Configuration with 2FA Plugins Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md A comprehensive example demonstrating the setup of Better Auth with various 2FA configurations, including TOTP, OTP, backup codes, and session management. ```typescript import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins"; import { sendEmail } from "./email"; export const auth = betterAuth({ appName: "My App", plugins: [ twoFactor({ // TOTP settings issuer: "My App", totpOptions: { digits: 6, period: 30, }, // OTP settings otpOptions: { sendOTP: async ({ user, otp }) => { await sendEmail({ to: user.email, subject: "Your verification code", text: `Your code is: ${otp}`, }); }, period: 5, allowedAttempts: 5, storeOTP: "encrypted", }, // Backup code settings backupCodeOptions: { amount: 10, length: 10, storeBackupCodes: "encrypted", }, // Session settings twoFactorCookieMaxAge: 600, // 10 minutes trustDeviceMaxAge: 30 * 24 * 60 * 60, // 30 days }), ], }); ``` -------------------------------- ### CI/CD Pipeline Script Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Example script for a CI/CD pipeline to migrate the database, build, and start the application. ```bash #!/bin/bash set -e npx @better-auth/cli migrate npm run build npm start ``` -------------------------------- ### Install Better Auth CLI Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Install the Better Auth CLI as a development dependency or run it directly using npx. ```bash npm install -D @better-auth/cli # or npx @better-auth/cli@latest ``` -------------------------------- ### Complete Security Configuration Example Source: https://github.com/better-auth/skills/blob/main/security/SKILL.MD A comprehensive example demonstrating various security settings including rate limiting, session management, OAuth, advanced configurations, and database hooks. ```typescript import { betterAuth } from "better-auth"; export const auth = betterAuth({ secret: process.env.BETTER_AUTH_SECRET, baseURL: "https://api.example.com", trustedOrigins: [ "https://app.example.com", "https://*.preview.example.com", ], // Rate limiting rateLimit: { enabled: true, storage: "secondary-storage", customRules: { "/api/auth/sign-in/email": { window: 60, max: 5 }, "/api/auth/sign-up/email": { window: 60, max: 3 }, }, }, // Session security session: { expiresIn: 60 * 60 * 24 * 7, // 7 days updateAge: 60 * 60 * 24, // 24 hours freshAge: 60 * 60, // 1 hour for sensitive actions cookieCache: { enabled: true, maxAge: 300, strategy: "jwe", // Encrypted session data }, }, // OAuth security account: { encryptOAuthTokens: true, storeStateStrategy: "cookie", }, // Advanced settings advanced: { useSecureCookies: true, cookiePrefix: "myapp", defaultCookieAttributes: { sameSite: "lax", }, ipAddress: { ipAddressHeaders: ["x-forwarded-for"], ipv6Subnet: 64, }, backgroundTasks: { handler: (promise) => waitUntil(promise), }, }, // Security auditing databaseHooks: { session: { create: { after: async ({ data, ctx }) => { console.log(`New session for user ${data.userId}`); }, }, }, user: { update: { after: async ({ data, oldData }) => { if (oldData?.email !== data.email) { console.log(`Email changed for user ${data.id}`); } }, }, }, }, }); ``` -------------------------------- ### Install Core Better Auth Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Install the core `better-auth` package using npm. ```bash npm install better-auth ``` -------------------------------- ### Comprehensive Better Auth Configuration Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/README.md A detailed example of how to configure Better Auth, including core settings, feature enablement, plugin integration, and advanced options. ```typescript export const auth = betterAuth({ // Core secret: process.env.BETTER_AUTH_SECRET, baseURL: process.env.BETTER_AUTH_URL, database: connectionOrAdapter, // Features emailAndPassword: { enabled: true }, socialProviders: { google: { ... } }, plugins: [ twoFactor({ ... }), organization({ ... }), ], // Advanced advanced: { ... }, hooks: { ... }, databaseHooks: { ... }, }); ``` -------------------------------- ### Client Setup Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Initialize the two-factor client plugin for your frontend application. ```APIDOC ## Client Setup Initialize the two-factor client plugin for your frontend application. ```typescript import { createAuthClient } from "better-auth/client"; import { twoFactorClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [ twoFactorClient({ onTwoFactorRedirect() { window.location.href = "/2fa"; }, }), ], }); ``` ``` -------------------------------- ### Server Setup Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Integrate the two-factor plugin into your Better Auth server configuration. ```APIDOC ## Server Setup Integrate the two-factor plugin into your Better Auth server configuration. ```typescript import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins"; export const auth = betterAuth({ appName: "My App", plugins: [ twoFactor({ issuer: "My App", // Displayed in authenticator app }), ], }); ``` ``` -------------------------------- ### Model Name Configuration Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Example showing how to configure model names for Prisma and Drizzle, mapping ORM model names to database table names. ```typescript // Prisma model 'User' → table 'users' user: { modelName: "user", // Use model name, not "users" fields: { name: "displayName", // Map field to column }, } // Drizzle table user: { modelName: "user", // Use Drizzle table name fields: { name: "display_name", // Map to column }, } ``` -------------------------------- ### Prisma Adapter Setup Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Use this to integrate Prisma with Better Auth. Ensure you have Prisma set up and the necessary provider configured. ```javascript prismaAdapter(prisma, { provider: "postgresql" }) ``` -------------------------------- ### Plugin Client Setup Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Set up the Better Auth client by importing `createAuthClient` and necessary client plugins. Configure the base URL and include desired plugins. ```typescript import { createAuthClient } from "better-auth/client"; import { twoFactorClient } from "better-auth/client/plugins"; import { organizationClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ baseURL: "http://localhost:3000", plugins: [ twoFactorClient(), organizationClient(), // ... other plugins ], }); ``` -------------------------------- ### OTP Setup - Server Configuration Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Configure the OTP (email/SMS) sending mechanism on the server. ```APIDOC ## Server Configuration ```typescript import { twoFactor } from "better-auth/plugins"; import { sendEmail } from "./email"; twoFactor({ otpOptions: { sendOTP: async ({ user, otp }, ctx) => { await sendEmail({ to: user.email, subject: "Your verification code", text: `Your code is: ${otp}`, }); }, period: 5, // 5 minutes digits: 6, // 6-digit code allowedAttempts: 5, // Max 5 attempts storeOTP: "encrypted", // Encrypted in database }, }); ``` ``` -------------------------------- ### Account Type Usage Examples Source: https://github.com/better-auth/skills/blob/main/_autodocs/types.md Provides examples for listing linked accounts and unlinking an account. ```typescript // List accounts const accounts = await auth.api.listAccounts({ headers }); ``` ```typescript // Unlink account await auth.api.unlinkAccount({ accountId: "account-id", }, { headers }); ``` -------------------------------- ### Install Scoped Better Auth Packages Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Install scoped packages for specific features like Passkey, SSO, Stripe, SCIM, Expo, etc., as needed. ```bash npm install @better-auth/passkey ``` ```bash npm install @better-auth/sso ``` ```bash npm install @better-auth/stripe ``` ```bash npm install @better-auth/scim ``` ```bash npm install @better-auth/expo ``` -------------------------------- ### Organization Type Usage Examples Source: https://github.com/better-auth/skills/blob/main/_autodocs/types.md Demonstrates creating a new organization and retrieving an existing one. ```typescript // Create organization const { data } = await authClient.organization.create({ name: "My Company", slug: "my-company", }); ``` ```typescript // Get organization const org = await auth.api.getOrganization({ organizationId: "org-id", }, { headers }); ``` -------------------------------- ### Client-Side Setup with Two-Factor Client Plugin Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md Set up the twoFactorClient plugin on the client, including a handler for 2FA redirects to the '/2fa' page. ```typescript import { createAuthClient } from "better-auth/client"; import { twoFactorClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [ twoFactorClient({ onTwoFactorRedirect() { window.location.href = "/2fa"; }, }), ], }); ``` -------------------------------- ### User Type Usage Examples Source: https://github.com/better-auth/skills/blob/main/_autodocs/types.md Demonstrates how to retrieve user data from the server and client, and how to infer the user type. ```typescript // From server const user = await auth.api.getUser({ headers }); ``` ```typescript // From client const { data: session } = await authClient.getSession(); const user = session?.user; ``` ```typescript // Type inference type AppUser = typeof auth.$Infer.Session.user; ``` -------------------------------- ### Client-Side Plugin Configuration Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Example of configuring the two-factor client plugin, including a handler for redirecting when 2FA is required. ```typescript import { createAuthClient } from "better-auth/client"; import { twoFactorClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [ twoFactorClient({ // Redirect on 2FA required onTwoFactorRedirect() { window.location.href = "/2fa"; }, }), ], }); ``` -------------------------------- ### TOTP Setup - Verify TOTP Code Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Verify a TOTP code to complete the 2FA setup or for subsequent logins. Optionally trust the device. ```APIDOC ## Verify TOTP Code ```typescript const { data, error } = await authClient.twoFactor.verifyTotp({ code: "123456", // 6-digit code trustDevice: true, // Optional: remember device }); ``` **Code acceptance window:** Accepts codes from 1 period before/after current time (±30 seconds default). ``` -------------------------------- ### MongoDB Adapter Setup Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Connect MongoDB to Better Auth using the mongodbAdapter. Pass your MongoDB database instance directly. ```javascript mongodbAdapter(db) ``` -------------------------------- ### OTP Setup - Verify OTP Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Verify the OTP code received by the user. Optionally trust the device for future logins. ```APIDOC ## Verify OTP ```typescript const { data, error } = await authClient.twoFactor.verifyOtp({ code: "123456", trustDevice: true, // Optional: remember device }); ``` ``` -------------------------------- ### Prisma Schema Extension Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Example of extending the Prisma schema with custom fields like 'plan' and mapping models to tables using '@@map'. ```prisma model User { id String @id @default(cuid()) email String @unique name String // Add custom fields plan String @default("free") @@map("users") } model Session { id String @id @default(cuid()) userId String token String @unique expiresAt DateTime @@map("sessions") } ``` -------------------------------- ### Complete Organization Configuration Example Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md This snippet shows a comprehensive configuration for the organization plugin in Better Auth, including limits, invitation settings, and hooks. ```typescript import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; import { sendEmail } from "./email"; export const auth = betterAuth({ plugins: [ organization({ // Organization limits allowUserToCreateOrganization: true, organizationLimit: 10, membershipLimit: 100, creatorRole: "owner", // Slugs defaultOrganizationIdField: "slug", // Invitations invitationExpiresIn: 60 * 60 * 24 * 7, // 7 days invitationLimit: 50, sendInvitationEmail: async (data) => { await sendEmail({ to: data.email, subject: `Join ${data.organization.name}`, html: `Accept`, }); }, // Hooks hooks: { organization: { afterCreate: async ({ organization }) => { console.log(`Organization ${organization.name} created`); }, }, }, }), ], }); ``` -------------------------------- ### Field to Column Mapping Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Example demonstrating how to map ORM fields to specific database column names within the Better Auth configuration. ```typescript user: { fields: { email: "userEmail", name: "displayName", }, } ``` -------------------------------- ### Multiple Plugins Order Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Illustrates the importance of plugin order, with core authentication methods and organization management plugins typically preceding advanced features like JWT or OpenAPI. ```typescript plugins: [ // Core auth methods first twoFactor({ issuer: "My App" }), // Then org/team management organization({ allowUserToCreateOrganization: true }), // Then advanced features jwt(), openAPI(), ] ``` -------------------------------- ### Client-Side Organization Plugin Setup Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md Configure the organization client plugin. This is necessary for client-side operations related to organizations. ```typescript import { createAuthClient } from "better-auth/client"; import { organizationClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [organizationClient()], }); ``` -------------------------------- ### Server Setup with Organization Plugin Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md Configure the Better Auth server with the organization plugin. Set limits for organizations and memberships, and control user creation permissions. ```typescript import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; export const auth = betterAuth({ plugins: [ organization({ allowUserToCreateOrganization: true, organizationLimit: 5, membershipLimit: 100, }), ], }); ``` -------------------------------- ### Prisma Output Format Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Example of the generated Prisma schema output. ```prisma model User { id String @id @default(cuid()) email String @unique name String // ... auth fields } ``` -------------------------------- ### TOTP Setup - Enable 2FA Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Enable Two-Factor Authentication using TOTP. Requires password verification and returns a TOTP URI for QR code generation and backup codes. ```APIDOC ## Enable 2FA (TOTP) Requires password verification. ```typescript const { data, error } = await authClient.twoFactor.enable({ password: "user-password", }); if (data) { // data.totpURI - for QR code generation // data.backupCodes - for user to save securely } ``` **Returns:** ```typescript { totpURI: string, // otpauth:// URI for QR code backupCodes: string[] // Recovery codes } ``` **Important:** 2FA not enabled until first TOTP code verified (unless `skipVerificationOnEnable: true`). ``` -------------------------------- ### Check Better Auth CLI Version Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Verify the installed version of the Better Auth CLI. ```bash npx @better-auth/cli --version ``` -------------------------------- ### Member Type Usage Examples Source: https://github.com/better-auth/skills/blob/main/_autodocs/types.md Shows how to add a new member to an organization and update a member's role. ```typescript // Add member await auth.api.addMember({ userId: "user-id", organizationId: "org-id", role: "member", }, { headers }); ``` ```typescript // Update role await authClient.organization.updateMemberRole({ memberId: "member-id", role: "admin", }); ``` -------------------------------- ### Social Providers Configuration Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/configuration.md Configure various social login providers by providing their respective client IDs and secrets. Ensure you obtain these credentials from the provider's developer portal. ```typescript socialProviders: { google: { clientId: string clientSecret: string } github: { clientId: string clientSecret: string } discord: { clientId: string clientSecret: string } // ... other providers } ``` -------------------------------- ### Drizzle Adapter Setup Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Integrate Drizzle ORM with Better Auth. This requires a Drizzle database instance and the correct provider specified. ```javascript drizzleAdapter(db, { provider: "pg" }) ``` -------------------------------- ### Plugin Hooks Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Demonstrates how to use lifecycle hooks like `beforeCreate` and `afterCreate` within a plugin configuration. These hooks allow for custom logic before or after an action. ```typescript pluginName({ hooks: { beforeCreate: async (data, ctx) => { // Runs before creation return data; // Can modify data }, afterCreate: async (data, ctx) => { // Runs after creation // Post-creation side effects }, }, }) ``` -------------------------------- ### Server Setup with Two-Factor Plugin Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Configure the Better Auth server with the two-factor plugin, specifying the issuer name for authenticator apps. ```typescript import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins"; export const auth = betterAuth({ appName: "My App", plugins: [ twoFactor({ issuer: "My App", // Displayed in authenticator app }), ], }); ``` -------------------------------- ### Run Generate Command Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Use the generate command to create schema files for ORM-based setups like Prisma or Drizzle. ```bash npx @better-auth/cli generate --output [options] ``` -------------------------------- ### Create Organization (Client-Side) Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md Create a new organization using the client-side setup. The creator is automatically assigned the 'owner' role. Optional fields include logo and metadata. ```typescript const createOrg = async () => { const { data, error } = await authClient.organization.create({ name: "My Company", slug: "my-company", logo: "https://example.com/logo.png", metadata: { plan: "pro" }, }); }; ``` -------------------------------- ### Full Server Configuration (auth.ts) Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Configure a full server setup for Better Auth, including plugins, session management, account linking, and rate limiting. ```typescript import { auth } from "better-auth"; import { DrizzleAdapter } from "@better-auth/drizzle-adapter"; import { db } from "../db"; // Your Drizzle instance export const { handlers, auth, signIn, signOut } = auth({ adapter: DrizzleAdapter(db, schema), // Example using Drizzle adapter plugins: [ // Add feature plugins here, e.g., twoFactor, organization ], session: { expires: "24h", // Session expiry maxAge: 60 * 60 * 24, // Session max age in seconds updateAge: 60 * 60, // Session update age in seconds }, account: { accountLinking: true, // Enable account linking for multiple providers }, rateLimit: { // Rate limiting configuration } }); export type Session = typeof auth.$Infer.Session; ``` -------------------------------- ### Server-Side Organization Plugin Setup Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md Configure the organization plugin on the server. Set limits for organizations per user and members per organization. Ensure the 'organization' table exists in your database. ```typescript import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; export const auth = betterAuth({ plugins: [ organization({ allowUserToCreateOrganization: true, organizationLimit: 5, // Max orgs per user membershipLimit: 100, // Max members per org }), ], }); ``` -------------------------------- ### Server-Side Setup with Two-Factor Plugin Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md Configure the twoFactor plugin on the server with a specified issuer. Ensure the 'twoFactorSecret' column exists on your user table after migration. ```typescript import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins"; export const auth = betterAuth({ appName: "My App", plugins: [ twoFactor({ issuer: "My App", }), ], }); ``` -------------------------------- ### Session Type Usage Examples Source: https://github.com/better-auth/skills/blob/main/_autodocs/types.md Shows how to infer the session type and check for an active session, accessing associated user data. ```typescript // Type inference type AppSession = typeof auth.$Infer.Session; ``` ```typescript // Check session const session = await auth.api.getSession({ headers }); if (session) { console.log(session.user.email); } ``` -------------------------------- ### PostgreSQL Direct Connection Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Connect directly to a PostgreSQL database using the 'pg' package. Ensure 'pg' is installed and DATABASE_URL is set. ```typescript import pg from "pg"; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, }); export const auth = betterAuth({ database: pool, }); ``` -------------------------------- ### MySQL Direct Connection Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Connect directly to a MySQL database using the 'mysql2/promise' package. Ensure 'mysql2' is installed and DATABASE_URL is set. ```typescript import mysql from "mysql2/promise"; const pool = mysql.createPool({ connectionString: process.env.DATABASE_URL, }); export const auth = betterAuth({ database: pool, }); ``` -------------------------------- ### TOTP Setup - Disable 2FA Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Disable Two-Factor Authentication. Requires password verification and revokes all trusted devices. ```APIDOC ## Disable 2FA Requires password verification. Revokes all trusted devices. ```typescript const { error } = await authClient.twoFactor.disable({ password: "user-password", }); ``` ``` -------------------------------- ### Setup Invitation Email Sending Source: https://github.com/better-auth/skills/blob/main/better-auth/organization/SKILL.md Customize the invitation email content and sending mechanism. This server-side configuration allows for personalized invitation emails. ```typescript import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; import { sendEmail } from "./email"; export const auth = betterAuth({ plugins: [ organization({ sendInvitationEmail: async (data) => { const { email, organization, inviter, invitation } = data; await sendEmail({ to: email, subject: `Join ${organization.name}`, html: `

${inviter.user.name} invited you to join ${organization.name}

Accept Invitation `, }); }, }), ], }); ``` -------------------------------- ### Complete Better Auth Security Configuration Source: https://github.com/better-auth/skills/blob/main/_autodocs/security.md A comprehensive Better Auth configuration example demonstrating various security settings including trusted origins, rate limiting, session security, OAuth security, and advanced options. ```typescript import { betterAuth } from "better-auth"; export const auth = betterAuth({ secret: process.env.BETTER_AUTH_SECRET, baseURL: "https://api.example.com", // Trusted origins trustedOrigins: [ "https://app.example.com", "https://*.preview.example.com", ], // Rate limiting rateLimit: { enabled: true, storage: "secondary-storage", customRules: { "/api/auth/sign-in/email": { window: 60, max: 5 }, "/api/auth/sign-up/email": { window: 60, max: 3 }, }, }, // Session security session: { expiresIn: 60 * 60 * 24 * 7, updateAge: 60 * 60 * 24, freshAge: 60 * 60, cookieCache: { enabled: true, maxAge: 300, strategy: "jwe", // Encrypted session data }, }, // OAuth security account: { encryptOAuthTokens: true, storeStateStrategy: "cookie", }, // Advanced settings advanced: { useSecureCookies: true, disableCSRFCheck: false, cookiePrefix: "myapp", defaultCookieAttributes: { sameSite: "lax", }, ipAddress: { ipAddressHeaders: ["x-forwarded-for"], ipv6Subnet: 64, }, backgroundTasks: { handler: (promise) => waitUntil(promise), }, }, // Audit logging databaseHooks: { session: { create: { after: async ({ data, ctx }) => { await auditLog("session.created", { userId: data.userId }); }, }, }, }, }); ``` -------------------------------- ### Plugin Schema Customization Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Shows how to customize plugin schema, including table names and field mappings. You can also add additional fields to the schema. ```typescript organization({ schema: { organization: { modelName: "workspace", // Custom table name fields: { name: "workspaceName", // Custom field mapping }, additionalFields: { plan: { type: "string", required: false }, }, }, }, }) ``` -------------------------------- ### Prisma ORM Adapter Configuration Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Configure the Prisma adapter for Better Auth. Requires '@prisma/client' and specific setup steps including schema generation and migration. ```typescript import { PrismaClient } from "@prisma/client"; import { prismaAdapter } from "better-auth/adapters/prisma"; const prisma = new PrismaClient(); export const auth = betterAuth({ database: prismaAdapter(prisma, { provider: "postgresql", // or "mysql", "sqlite" }), }); ``` -------------------------------- ### Displaying QR Code for TOTP Setup Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md A React component to display a QR code generated from a TOTP URI. Requires the 'react-qr-code' library. ```tsx import QRCode from "react-qr-code"; const TotpSetup = ({ totpURI }: { totpURI: string }) => { return ; }; ``` -------------------------------- ### Run Info Command Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Display detailed information about your Better Auth configuration, including detected framework, adapter, plugins, and environment variables. ```bash npx @better-auth/cli info ``` -------------------------------- ### Initialize Better Auth Instance Source: https://github.com/better-auth/skills/blob/main/_autodocs/core-api.md Demonstrates how to create and configure a Better Auth server instance with various options like database, secret, app name, email/password, social providers, and plugins. ```typescript import { betterAuth } from "better-auth"; export const auth = betterAuth({ database: prisma, secret: process.env.BETTER_AUTH_SECRET, baseURL: process.env.BETTER_AUTH_URL, appName: "My App", emailAndPassword: { enabled: true, }, socialProviders: { google: { clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }, }, plugins: [ twoFactor({ issuer: "My App" }), ], }); ``` -------------------------------- ### Drizzle Schema Extension Example Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Example of extending the Drizzle schema with custom fields like 'plan' for users and defining session table structure. ```typescript export const users = pgTable("users", { id: text().primaryKey(), email: text().notNull().unique(), name: text().notNull(), plan: text().default("free"), }); export const sessions = pgTable("sessions", { id: text().primaryKey(), userId: text().notNull(), token: text().notNull().unique(), expiresAt: timestamp().notNull(), }); ``` -------------------------------- ### Configuring OTP Email Delivery Source: https://github.com/better-auth/skills/blob/main/better-auth/twoFactor/SKILL.md Set up custom OTP delivery via email. This example uses a placeholder 'sendEmail' function and configures code validity period, digits, and allowed attempts. ```typescript import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins"; import { sendEmail } from "./email"; export const auth = betterAuth({ plugins: [ twoFactor({ otpOptions: { sendOTP: async ({ user, otp }, ctx) => { await sendEmail({ to: user.email, subject: "Your verification code", text: `Your code is: ${otp}`, }); }, period: 5, // Code validity in minutes (default: 3) digits: 6, // Number of digits (default: 6) allowedAttempts: 5, // Max verification attempts (default: 5) }, }), ], }); ``` -------------------------------- ### Drizzle Output Format Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Example of the generated Drizzle schema output. ```typescript export const users = pgTable("users", { id: text().primaryKey(), email: text().notNull().unique(), name: text().notNull(), // ... auth fields }); ``` -------------------------------- ### Client Sign Up with Email Source: https://github.com/better-auth/skills/blob/main/_autodocs/authentication-methods.md Use the client-side SDK to sign up a new user with their email and password. Ensure the callbackURL is correctly configured. ```typescript const { data, error } = await authClient.signUp.email({ email: "user@example.com", password: "secure-password", name: "User Name", callbackURL: "https://app.example.com/callback", dontAutoSignIn: false, }); ``` -------------------------------- ### Run Migrate Command (Built-in Kysely Adapter) Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Execute the migrate command for the built-in Kysely adapter, which automatically applies schema changes. ```bash npx @better-auth/cli migrate ``` -------------------------------- ### Sign Up with Email Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md Register a new user using their email and password. Callbacks can handle success or error states, including redirecting the user. ```typescript const { data, error } = await authClient.signUp.email({ email: "user@example.com", password: "secure-password", name: "User Name", callbackURL?: "https://app.example.com/callback", dontAutoSignIn?: false, }, { onSuccess(context) { // Handle success - session is created window.location.href = "/dashboard"; }, onError(context) { // Handle error console.error(context.error.message); } }); ``` -------------------------------- ### Configure passkey Plugin Client Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Initialize the passkey client plugin. This typically requires no configuration options for basic usage. ```typescript import { passkeyClient } from "@better-auth/passkey/client"; plugins: [passkeyClient()] ``` -------------------------------- ### Get Organization Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md Fetches detailed information about a specific organization, including its members, pending invitations, and associated teams. ```APIDOC ## Get Organization ```typescript const { data, error } = await authClient.organization.getFullOrganization({ organizationId: "org-id", }); // Returns: { organization, members, invitations, teams } ``` ``` -------------------------------- ### Load Environment Variables from .env File Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Load Better Auth and database configuration from a .env file. ```bash # .env BETTER_AUTH_SECRET=... DATABASE_URL=... npx @better-auth/cli migrate ``` -------------------------------- ### SQLite Direct Connection (Node.js) Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Connect directly to a SQLite database using the 'better-sqlite3' library. Ensure 'better-sqlite3' is installed. ```typescript import Database from "better-sqlite3"; const db = new Database("./auth.db"); export const auth = betterAuth({ database: db, // Pass instance directly }); ``` -------------------------------- ### Configure Passkey Plugin Source: https://github.com/better-auth/skills/blob/main/_autodocs/authentication-methods.md Sets up the WebAuthn passkey plugin. Requires configuration of the relying party ID, name, and origin URL for security. ```typescript import { passkey } from "@better-auth/passkey"; plugins: [ passkey({ rpID: "example.com", // Domain name (no https://) rpName: "My App", // Display name origin: "https://example.com", // Full origin URL }), ] ``` -------------------------------- ### Run Migrate Command with Custom Config Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Use the migrate command with a custom configuration file path. ```bash npx @better-auth/cli migrate --config src/config/auth.ts ``` -------------------------------- ### Client-side Session Check Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Use the `useSession` hook in the client to get session data. It returns `{ data: session, isPending }`. ```javascript useSession() ``` -------------------------------- ### Vercel Build Step Configuration Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Configure the build command and environment variables in vercel.json for deployment. ```json { "buildCommand": "npm run db:push && npm run build", "env": { "DATABASE_URL": "@database_url", "BETTER_AUTH_SECRET": "@auth_secret" } } ``` -------------------------------- ### betterAuth() Source: https://github.com/better-auth/skills/blob/main/_autodocs/core-api.md Initializes and configures a Better Auth server instance with provided options. This is the primary function to set up the authentication system. ```APIDOC ## betterAuth() ### Description Creates and configures a Better Auth server instance. ### Signature ```typescript betterAuth(options: InitOptions): Auth ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | options | InitOptions | Yes | — | Configuration object for auth instance | ### Return Type ```typescript Auth { handler: (request: Request) => Promise api: { getSession(options: { headers: Headers }): Promise signInEmail(body: SignInEmailBody): Promise signUpEmail(body: SignUpEmailBody): Promise signOut(options: { headers: Headers }): Promise requestPasswordReset(body: { email: string; redirectTo?: string }): Promise resetPassword(body: { newPassword: string; token: string }): Promise changePassword(body: { oldPassword: string; newPassword: string }, options: { headers: Headers }): Promise changeEmail(body: { newEmail: string }, options: { headers: Headers }): Promise getUser(options: { headers: Headers }): Promise listSessions(options: { headers: Headers }): Promise revokeSession(options: { headers: Headers; body: { token: string } }): Promise revokeSessions(options: { headers: Headers }): Promise listAccounts(options: { headers: Headers }): Promise unlinkAccount(body: { accountId: string }, options: { headers: Headers }): Promise createOrganization?(body: CreateOrganizationBody, options?: { headers: Headers }): Promise addMember?(body: AddMemberBody, options?: { headers: Headers }): Promise removeMember?(body: { memberIdOrEmail: string }, options?: { headers: Headers }): Promise updateMemberRole?(body: UpdateMemberRoleBody, options?: { headers: Headers }): Promise inviteMember?(body: InviteMemberBody, options?: { headers: Headers }): Promise listMembers?(options?: { headers: Headers }): Promise listInvitations?(options?: { headers: Headers }): Promise listOrganizations?(options?: { headers: Headers }): Promise getOrganization?(body: { organizationId: string }, options?: { headers: Headers }): Promise } $Infer: { Session: typeof session } } ``` ### Usage Example ```typescript import { betterAuth } from "better-auth"; export const auth = betterAuth({ database: prisma, secret: process.env.BETTER_AUTH_SECRET, baseURL: process.env.BETTER_AUTH_URL, appName: "My App", emailAndPassword: { enabled: true, }, socialProviders: { google: { clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }, }, plugins: [ twoFactor({ issuer: "My App" }), ], }); ``` ### Framework Handlers Convert the Auth instance to a framework-specific handler: ```typescript // Next.js App Router import { toNextJsHandler } from "better-auth/next-js"; export const { GET, POST } = toNextJsHandler(auth); // Express import { toNodeHandler } from "better-auth/node"; app.all("/api/auth/*", toNodeHandler(auth)); // SvelteKit import { svelteKitHandler } from "better-auth/svelte-kit"; export const { GET, POST } = svelteKitHandler(auth); // Hono import { toHonoHandler } from "better-auth/hono"; app.all("/api/auth/*", toHonoHandler(auth)); ``` ``` -------------------------------- ### Configure Database Adapter for Drizzle Source: https://github.com/better-auth/skills/blob/main/better-auth/best-practices/SKILL.md Import and configure the Drizzle ORM adapter for Better Auth. Ensure your Drizzle setup is compatible. ```typescript import { DrizzleAdapter } from "better-auth/adapters/drizzle"; ``` -------------------------------- ### Plugin Configuration Pattern Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Illustrates the general pattern for configuring plugins with optional settings. If options are omitted, default values are used. ```typescript pluginName(options?: { // Configuration options // Each plugin defines its own options }) If `options` omitted, uses defaults. ``` -------------------------------- ### Get Invitation URL Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md Generates a unique URL for an invitation. This URL can be shared with the invitee to accept the invitation. This method does not send an email. ```APIDOC ## GET /organization/invitation-url ### Description Generates a unique URL for an invitation. This URL can be shared with the invitee to accept the invitation. This method does not send an email. ### Method GET ### Endpoint /organization/invitation-url ### Parameters #### Query Parameters - **email** (string) - Required - The email address of the person to invite. - **role** (string) - Required - The role to assign to the invited member (e.g., "member", "admin"). - **callbackURL** (string) - Optional - A URL to redirect the user to after accepting the invitation. - **organizationId** (string) - Optional - The ID of the organization. If omitted, the active organization is used. ### Response #### Success Response (200) - **url** (string) - The unique URL for the invitation. #### Response Example ```json { "url": "https://app.example.com/accept-invite/inv-12345" } ``` ``` -------------------------------- ### Get Session (Any Framework) Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md Fetch the current user's session data directly using the auth client. This method is framework-agnostic. ```typescript const session = await authClient.getSession(); if (session) { console.log(session.user.email); } else { // Not authenticated } ``` -------------------------------- ### Set DATABASE_URL for Connection Issues Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Troubleshoot 'Database connection failed' errors by ensuring the DATABASE_URL environment variable is correctly set. ```bash DATABASE_URL=postgresql://user:password@localhost/dbname \ npx @better-auth/cli migrate ``` -------------------------------- ### Minimal Server Configuration (auth.ts) Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Set up the minimal server configuration for Better Auth, requiring at least a database connection or adapter and enabling email/password authentication. ```typescript import { auth } from "better-auth"; export const { handlers, auth, signIn, signOut } = auth({ database: { // Connection or adapter details here }, emailAndPassword: { enabled: true }, }); export type Session = typeof auth.$Infer.Session; ``` -------------------------------- ### Get Invitation URL Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md Retrieve a unique URL for invitation acceptance. The `organizationId` is optional and defaults to the active organization. The `callbackURL` is also optional. ```typescript const { data, error } = await authClient.organization.getInvitationURL({ email: "newuser@example.com", role: "member", callbackURL: "https://app.example.com/dashboard", // Optional organizationId?: "org-id", // Uses active if omitted }); // Share data.url via email, Slack, etc. // Does NOT call sendInvitationEmail ``` -------------------------------- ### Get Full Organization Details Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md Fetch detailed information about a specific organization, including its members, invitations, and teams, using the client-side method. ```typescript const { data, error } = await authClient.organization.getFullOrganization({ organizationId: "org-id", }); // Returns: { organization, members, invitations, teams } ``` -------------------------------- ### Create Auth Client (Vanilla JS) Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md Instantiate the client for browser-side authentication operations. Ensure the baseURL matches your auth API configuration. ```typescript import { createAuthClient } from "better-auth/client"; export const authClient = createAuthClient({ baseURL: "http://localhost:3000", }); ``` -------------------------------- ### Set Custom Invitation Expiration Source: https://github.com/better-auth/skills/blob/main/_autodocs/organization-plugin.md Configure the expiration time for organization invitations. The default is 48 hours. This example sets the expiration to 7 days. ```typescript organization({ invitationExpiresIn: 60 * 60 * 24 * 7, // 7 days }); ``` -------------------------------- ### Database Migration CLI Commands Source: https://github.com/better-auth/skills/blob/main/_autodocs/database-adapters.md Run these commands to manage database migrations for different adapters. Always re-run after adding or changing plugins. ```bash # For built-in Kysely adapter npx @better-auth/cli@latest migrate # For Prisma npx @better-auth/cli@latest generate --output prisma/schema.prisma npx prisma migrate dev # For Drizzle npx @better-auth/cli@latest generate --output src/db/auth-schema.ts npx drizzle-kit push ``` -------------------------------- ### Configure organization Plugin Client Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Initialize the organization client plugin. This typically requires no configuration options for basic usage. ```typescript import { organizationClient } from "better-auth/client/plugins"; plugins: [organizationClient()] ``` -------------------------------- ### Better Auth CLI: Generate Prisma Schema Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Generate the Prisma schema file using the Better Auth CLI, then run Prisma migrations. ```bash npx @better-auth/cli@latest generate --output prisma/schema.prisma npx prisma migrate dev ``` -------------------------------- ### SCIM Plugin Server Import Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Import and configure the SCIM plugin for user provisioning. Requires a secret key from environment variables. ```typescript import { scim } from "@better-auth/scim"; plugins: [ scim({ secret: process.env.SCIM_SECRET, }), ] ``` -------------------------------- ### OTP Setup - Send OTP Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Send an OTP code to the user's registered email or phone number. This triggers the `sendOTP` handler configured on the server. ```APIDOC ## Send OTP ```typescript const { error } = await authClient.twoFactor.sendOtp(); // Triggers sendOTP handler configured on server ``` ``` -------------------------------- ### Client Configuration for Vanilla JS Source: https://github.com/better-auth/skills/blob/main/better-auth/create-auth/SKILL.md Import and configure the Better Auth client for Vanilla JavaScript applications using the `better-auth/client` package. Client plugins can be included in the configuration. ```typescript import { createAuthClient } from "better-auth/client"; const { signIn, signUp, signOut, useSession, getSession } = createAuthClient({ // Add client plugins here if needed // plugins: [ // ... // ] }); export { signIn, signUp, signOut, useSession, getSession }; ``` -------------------------------- ### Configure passkey Plugin on Server Source: https://github.com/better-auth/skills/blob/main/_autodocs/plugins.md Enable WebAuthn/FIDO2 passwordless authentication. Configure Relying Party ID, name, and origin for secure passkey operations. ```typescript import { passkey } from "@better-auth/passkey"; plugins: [ passkey({ rpID: "example.com", rpName?: "My App", origin: "https://example.com", }), ] ``` -------------------------------- ### twoFactor.verifyTotp() Source: https://github.com/better-auth/skills/blob/main/_autodocs/client-api.md Verifies a Time-based One-Time Password (TOTP) code, typically used during sign-in or setup. It can accept codes from a small time window around the current time. ```APIDOC ## twoFactor.verifyTotp() ### Description Verifies a TOTP code during signin or setup. Accepts codes from the period before/after the current time (window = 1). ### Method Not specified (assumed to be a client-side SDK method call) ### Parameters #### Request Body - **code** (string) - Required - The 6-digit TOTP code. - **trustDevice** (boolean) - Optional - A flag to remember the device. ``` -------------------------------- ### Enable 2FA (TOTP) with Password Verification Source: https://github.com/better-auth/skills/blob/main/_autodocs/two-factor-plugin.md Initiate the 2FA enablement process by providing the user's password. This returns a TOTP URI for QR code generation and backup codes. ```typescript const { data, error } = await authClient.twoFactor.enable({ password: "user-password", }); if (data) { // data.totpURI - for QR code generation // data.backupCodes - for user to save securely } ``` -------------------------------- ### Run Migrate with Environment Variables Source: https://github.com/better-auth/skills/blob/main/_autodocs/cli-reference.md Set environment variables like BETTER_AUTH_SECRET and DATABASE_URL before running the migrate command. ```bash BETTER_AUTH_SECRET=your-secret BETTER_AUTH_URL=https://api.example.com DATABASE_URL=postgresql://... npx @better-auth/cli migrate ```