new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Better Auth · all subjects

installation & setup

40 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

OAuth Provider Plugin Installation

The OAuth provider plugin for Better Auth can be installed using npm with the command: npm install @better-auth/oauth-provider

Self-host anywhere with full control

Better Auth can be deployed on your own infrastructure with full control over deployment.

Flexible deployment options

Better Auth supports flexible deployment: run alongside your app or as a standalone self-hosted auth server.

better-auth/minimal limitations

The `better-auth/minimal` version does not support direct database connections and built-in migrations are not supported. An adapter must be used, and external migration tools are required or you must use the full `better-auth` package for built-in migration support.

better-auth/minimal for bundle size reduction

Use `better-auth/minimal` instead of `better-auth` when using custom adapters (Prisma, Drizzle, or MongoDB) to reduce bundle size. This version excludes Kysely, which is only needed for direct database connections.

BETTER_AUTH_API_KEY environment variable

Set the BETTER_AUTH_API_KEY environment variable in your production environment with the API key obtained from the Better Auth Infrastructure dashboard. This is required.

Better Auth Infrastructure prerequisites

Before integrating Better Auth Infrastructure, you must have a working Better Auth installation and an account with API Key from the Better Auth Infrastructure dashboard.

Install @better-auth/infra package

Install the @better-auth/infra package to enable Better Auth Infrastructure features.

Mount Better Auth handlers on Convex deployment

Create `convex/http.ts` that imports httpRouter from 'convex/server', authComponent and createAuth from './betterAuth/auth'. Create http router, call `authComponent.registerRoutes(http, createAuth)`, and export the http router.

Install Better Auth and Convex integration packages

Install Better Auth and the Convex component using: `npm install better-auth @convex-dev/better-auth`. The `@convex-dev/better-auth` package is maintained by Convex.

Set Convex environment variables for Better Auth

Generate and set a BETTER_AUTH_SECRET using `npx convex env set BETTER_AUTH_SECRET=$(openssl rand -base64 32)` or `npx auth secret`. Set SITE_URL using `npx convex env set SITE_URL http://localhost:3000`. Environment variables for the auth instance like BETTER_AUTH_SECRET, GITHUB_CLIENT_ID, and GITHUB_CLIENT_SECRET should be configured through the Convex CLI or dashboard, not in .env.local.

.env.local configuration for Convex Better Auth (self-hosted deployment)

For self-hosted deployments, configure .env.local with: CONVEX_DEPLOYMENT (format: dev:adjective-animal-123), NEXT_PUBLIC_CONVEX_URL (format: http://127.0.0.1:3210), NEXT_PUBLIC_CONVEX_SITE_URL (generally one port number higher than NEXT_PUBLIC_CONVEX_URL, format: http://127.0.0.1:3211), and NEXT_PUBLIC_SITE_URL (local site URL, format: http://localhost:3000).

Create convex/auth.config.ts for Better Auth provider

Add a file at `convex/auth.config.ts` that imports `getAuthConfigProvider` from '@convex-dev/better-auth/auth-config' and exports an AuthConfig object with providers array containing the result of `getAuthConfigProvider()`.

Create Better Auth instance for Convex component

Create `convex/betterAuth/auth.ts` that: (1) imports createClient from '@convex-dev/better-auth', convex plugin, betterAuth function, and necessary types; (2) exports authComponent created with `createClient<DataModel, typeof schema>(components.betterAuth, {local: {schema}, verbose: false})`; (3) exports createAuthOptions function that returns BetterAuthOptions with appName, baseURL (process.env.SITE_URL), secret (process.env.BETTER_AUTH_SECRET), database (authComponent.adapter(ctx)), emailAndPassword enabled, and convex plugin with authConfig; (4) exports options for auth CLI; (5) exports createAuth function that returns betterAuth(createAuthOptions(ctx)).

Register Better Auth component in Convex app

Create or modify `convex/convex.config.ts` to import `defineApp` from 'convex/server' and the betterAuth component, create an app instance with `defineApp()`, call `app.use(betterAuth)`, and export the app.

Create Convex component definition for Better Auth

Create `convex/betterAuth/convex.config.ts` that imports `defineComponent` from 'convex/server', defines a component with `defineComponent('betterAuth')`, and exports it. This signals to Convex that the `convex/betterAuth` directory is a locally installed component.

Convex project prerequisites and setup

To integrate Better Auth with Convex, first create a Convex project using `npm create convex@latest` with user authentication set to 'none'. Then run `npx convex dev` during setup to initialize the Convex deployment and keep it running to maintain generated types.

Generate Convex Better Auth schema

After configuring the Better Auth instance in `convex/betterAuth/auth.ts`, run `npx auth generate --config ./convex/betterAuth/auth.ts --output ./convex/betterAuth/schema.ts` to generate the schema file. This command should be rerun if the Better Auth instance is modified.

Export Convex Better Auth adapter functions

Create `convex/betterAuth/adapter.ts` that imports `createApi` from '@convex-dev/better-auth', `createAuthOptions` from './auth', and schema. Export destructured functions from `createApi(schema, createAuthOptions)`: create, findOne, findMany, updateOne, updateMany, deleteOne, deleteMany.

SMS response handling example

Example: const result = await sendSMS({ to: '+1234567890', code: '123456', template: 'phone-verification' }); if (result.success) { console.log('SMS sent:', result.messageId); } else { console.error('Failed to send SMS:', result.error); } This shows how to handle the SendSMSResult response.

SMS service intended use

SMS delivery is intended to only be used for authentication flows.

SMS service features overview

The SMS service offers pre-built SMS templates for common auth flows, E.164 phone number format support, type-safe template variables, no infrastructure to manage, and global delivery support.

SMS template: sign-in-otp

sign-in-otp template sends a one-time password for passwordless sign-in. Example message: 'Your sign-in code is 123456. It expires in 10 minutes.'

SMS default template

If no template is specified, a generic verification message is sent. Example message: 'Your verification code is 123456.'

E.164 phone number format required

Phone numbers must be in E.164 format: +[country code][number]. Examples: US +14155551234, UK +447911123456, Germany +4915112345678, Japan +819012345678. Common mistakes: missing + prefix, including spaces, including dashes, including parentheses.

SMS service package import

The SMS service is included in the @better-auth/infra package. Import sendSMS and createSMSSender from @better-auth/infra.

sendSMS single message function

sendSMS is an async function that sends a single SMS message. It takes SendSMSOptions and optional SMSConfig, returning a Promise<SendSMSResult>. Signature: async function sendSMS(options: SendSMSOptions, config?: SMSConfig): Promise<SendSMSResult>

sendSMS options parameters

SendSMSOptions has three properties: to (string, required, phone number in E.164 format), code (string, required, the OTP code to send), and template (SMSTemplateId, optional, defaults to generic).

createSMSSender reusable instance

createSMSSender creates a reusable SMS sender instance that takes optional SMSConfig. The sender has a send method that takes SendSMSOptions. Usage: const sender = createSMSSender(config?: SMSConfig); await sender.send(options: SendSMSOptions);

SMSConfig interface

SMSConfig interface has two properties: apiKey (string, optional, Your Better Auth Infrastructure API key) and apiUrl (string, optional, Custom API URL).

SMS service environment variables

The SMS service automatically reads from BETTER_AUTH_API_KEY (required) and BETTER_AUTH_API_URL (optional, defaults to https://api.betterauth.com).

SMS template: phone-verification

phone-verification template sends a verification code for phone number verification. Example message: 'Your verification code is 123456. It expires in 10 minutes.'

SMS template: two-factor

two-factor template sends a two-factor authentication code. Example message: 'Your two-factor authentication code is 123456. Do not share this code with anyone.'

SendSMSResult response interface

SendSMSResult interface has three properties: success (boolean), messageId (string, optional, SMS provider message ID), and error (string, optional, error message if failed).

SMS error handling scenarios

Common SMS error scenarios include: 'API key not configured' when BETTER_AUTH_API_KEY is missing, 'Invalid phone number' when phone number is not in E.164 format, and other delivery errors.

SMS service automatic integration with phone plugin

When using dash() or sentinel() plugins with Better Auth's phone authentication, SMS messages are automatically sent for phone number verification, phone-based two-factor authentication, and phone OTP sign-in. Manual sendSMS() calls are not needed for these flows as the plugins handle it automatically.

Phone plugin with dash integration example

Example: betterAuth configured with phoneNumber plugin and dash() plugin. The phoneNumber plugin has sendOTP callback that can be customized, but when dash() is configured it handles SMS automatically.

SMS service plan requirements

Transactional SMS is available on Pro plans and above. Starter plan does not include Transactional SMS. Pro, Business, and Enterprise plans all include Transactional SMS.

sendSMS single message example

Example: await sendSMS({ to: '+1234567890', code: '123456', template: 'phone-verification' }); This sends a single SMS message with the specified phone number, code, and template.

createSMSSender with environment variables example

Example: const smsSender = createSMSSender({ apiKey: process.env.BETTER_AUTH_API_KEY, apiUrl: process.env.BETTER_AUTH_API_URL }); await smsSender.send({ to: '+1234567890', code: '123456', template: 'two-factor' }); This creates a reusable sender and sends SMS.

Give your agent this brain