← Back to dashboard
better-authauthfreshReader view (for NotebookLM)

Better Auth Integration Guide

What is Better Auth?

The real model

Self-hosted TypeScript auth where the trade-off is ownership for ops, and every default is a knob.

lib/auth.ts is server-only — it imports the DB driver and reads the secret, so importing it from a client component drags both into the bundle. nextCookies() must be the LAST plugin in the array or later plugins never get cookies written. Middleware's getSessionCookie() checks presence, not validity, so the Next.js 16 proxy.ts (the renamed middleware, exporting proxy) is a redirect optimisation and never an authorization boundary — re-check with auth.api.getSession({ headers: await headers() }) in every protected route. Run 1.7.7 or later (a critical Magic Link takeover was patched there) and upgrade core plus every @better-auth/* package together with npx auth upgrade. session.cookieCache trades correctness for latency: a revoked session stays live on other devices until maxAge expires. For codeAmani, the case is sharpest on the Kenya-targeted builds — a per-MAU bill in USD against KES revenue does not survive the spreadsheet, and the phoneNumber plugin makes SMS OTP a primary credential (store E.164 +2547XXXXXXXX, convert to 254XXXXXXXXX only at the M-Pesa boundary, and wire sendOTP to Africa's Talking or the $0.09/SMS Better Auth Infrastructure service) for users who have a reliable phone and no reliable email.

Six Better Auth primitives

One server instance, one mounted route, one typed client — plugins extend all three at once.

Text
██████╗ ███████╗████████╗████████╗███████╗██████╗      █████╗ ██╗   ██╗████████╗██╗  ██╗
██╔══██╗██╔════╝╚══██╔══╝╚══██╔══╝██╔════╝██╔══██╗    ██╔══██╗██║   ██║╚══██╔══╝██║  ██║
██████╔╝█████╗     ██║      ██║   █████╗  ██████╔╝    ███████║██║   ██║   ██║   ███████║
██╔══██╗██╔══╝     ██║      ██║   ██╔══╝  ██╔══██╗    ██╔══██║██║   ██║   ██║   ██╔══██║
██████╔╝███████╗   ██║      ██║   ███████╗██║  ██║    ██║  ██║╚██████╔╝   ██║   ██║  ██║
╚═════╝ ╚══════╝   ╚═╝      ╚═╝   ╚══════╝╚═╝  ╚═╝    ╚═╝  ╚═╝ ╚═════╝    ╚═╝   ╚═╝  ╚═╝

Better Auth Integration Guide

Focus: framework-agnostic, self-hosted TypeScript auth — email/password, social OAuth, sessions, and a first-party plugin ecosystem (organizations, 2FA, passkeys, phone OTP, Stripe billing) running entirely inside your own Next.js 16 app and your own Postgres.

Overview

Better Auth is a library, not a service. You call betterAuth({...}) in your own code, point it at your own database, and mount a single catch-all route. No external identity provider sits in the request path — signing in writes a row to your session table and sets an HttpOnly cookie signed with your BETTER_AUTH_SECRET.

That inversion is the whole trade-off against Clerk and Auth0:

Clerk / Auth0Better Auth
User data lives inthe vendor's databaseyour Postgres (user, session, account, verification)
Joining users to app datawebhook-synced mirror tablea plain SQL JOIN
Pricingper monthly-active-useryour database bill (framework is free, MIT)
Pre-built UIhosted componentsyou build the forms
Email / SMS deliveryincludedyou wire it (Resend, Africa's Talking) — or pay for Better Auth Infrastructure
Ops burdennonemigrations, secret rotation, table security

Versions (verified 2026-10-20 via npm view)

PackageVersionNotes
better-auth1.7.11 (latest)1.8.0-beta.1 is on the beta tag — not for production
auth (CLI)1.7.11requires Node ≥ 22.12
@better-auth/drizzle-adapter, @better-auth/prisma-adapter1.7.11split out of core; still re-exported as better-auth/adapters/*
@better-auth/passkey, @better-auth/stripe1.7.11upgrade in lockstep with core
stripe (peer of @better-auth/stripe)≤ 22.x (22.6.2)peer range is ^18 – ^22; stripe@23.0.0 is out but not supported yet
next peer range^14 || ^15 || ^16Next 16.4.2 current
drizzle-orm peer range^0.45.2 || >=1.0.0-rc.1 <2
prisma / @prisma/client peer range^5 || ^6 || ^7Prisma 8 is still RC

Official Documentation

Every docs page is available as Markdown by appending .md (e.g. https://better-auth.com/docs/integrations/next.md). Use https://better-auth.com/sitemap.xml to discover pages; llms.txt is only a short index.


Setup

1. Install

Bash
npm install better-auth@1.7.11
npm install @better-auth/drizzle-adapter@1.7.11   # if you use Drizzle

2. Generate a secret

BETTER_AUTH_SECRET signs session cookies and encrypts stored OAuth tokens. It must be high-entropy and at least 32 characters. The CLI generates one:

Bash
npx auth@latest secret

CLI package name: the CLI ships as the bare npm package auth (npx auth ...) and needs Node 22.12+. The old @better-auth/cli name is frozen at 1.4.21; never use it against a 1.7 install.

3. Environment variables

Secrets (store in Hazina / Vercel env, never NEXT_PUBLIC_*):

Bash
# .env.local — server-side only
BETTER_AUTH_SECRET=<32+ char secret from npx auth secret>
DATABASE_URL=<pooled postgres connection string>
GOOGLE_CLIENT_SECRET=<from Google Cloud console>
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

Non-secret settings:

VariableExamplePurpose
BETTER_AUTH_URLhttp://localhost:3000Base URL Better Auth builds callback URLs from
NEXT_PUBLIC_APP_URLhttps://app.example.comClient baseURL — only needed when auth runs on another origin
GOOGLE_CLIENT_ID1234-abc.apps.googleusercontent.comOAuth client ID (public by design)
STRIPE_PRO_PRICE_IDprice_...Stripe Price for the pro plan

Secret resolution: options.secret → BETTER_AUTH_SECRET → AUTH_SECRET; it throws in production when none is set. For rotation without logging everyone out, use versioned secrets — secrets: [{ version: 2, value }, { version: 1, value }] or the BETTER_AUTH_SECRETS env var in the form 2:<new>,1:<old> (first entry encrypts, the rest only decrypt). See https://better-auth.com/docs/reference/options#secrets.

4. Create the auth instance

lib/auth.ts — this module imports your database driver and reads the secret, so it is server-only. Never import it from a client component. Full typed version: examples/auth.ts.

TypeScript
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { nextCookies } from "better-auth/next-js";
import { db } from "@/lib/db";

export const auth = betterAuth({
  database: drizzleAdapter(db, { provider: "pg" }),
  emailAndPassword: { enabled: true },
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    },
  },
  plugins: [nextCookies()], // MUST be the last entry in this array
});

nextCookies() post-processes the response to write cookies set during server actions. Any plugin listed after it never gets its cookies written — still the most common misconfiguration.

5. Database adapters (Postgres, Neon, Supabase)

OptionImportMigrations
Raw pg Pool (built-in Kysely)new Pool({ connectionString }) passed as databasenpx auth@latest migrate applies them
DrizzledrizzleAdapter from @better-auth/drizzle-adapter (Relations v2: @better-auth/drizzle-adapter/relations-v2)npx auth@latest generate → drizzle-kit generate → drizzle-kit migrate
Prisma 7prismaAdapter from better-auth/adapters/prisma (package: @better-auth/prisma-adapter)npx auth@latest generate → prisma migrate dev
TypeScript
// Prisma 7 needs a driver adapter on the client
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@/generated/prisma/client";
import { prismaAdapter } from "better-auth/adapters/prisma";

const prisma = new PrismaClient({
  adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL as string }),
});
// database: prismaAdapter(prisma, { provider: "postgresql" })
  • Neon: use the pooled string (-pooler host). Any of the three options works; Drizzle + pg is the codeAmani default (see neon/).
  • Supabase: connect through the Supavisor pooler (transaction mode, port 6543). Better Auth talks to Postgres directly and bypasses PostgREST — see Security below. To keep auth tables out of public, set database.schemaName (Kysely, since 1.7.5) or drizzleAdapter(db, { provider: "pg", schemaName }). Do not name it auth on Supabase — that schema belongs to Supabase Auth. Use better_auth.
  • Joins: advanced: { database: { joins: true } } (moved out of experimental in 1.7) gives 2–3× faster /get-session and /get-full-organization. Drizzle needs relations in the schema — regenerate.

6. Create the tables

Bash
npx auth@latest generate          # ORM adapters: emits schema for your tool
npx auth@latest migrate           # built-in Kysely adapter only
npx auth@latest check schema      # read-only schema check (1.7.6+); for Drizzle/Prisma it checks your schema files, not applied migrations

Core tables: user, session, account, verification, plus one table per schema-carrying plugin. Field facts:

  • account.password holds the password hash. It exists even with email/password disabled and is marked non-returned. Same for accessToken / refreshToken / idToken.
  • session.token is unique; session.userId is a cascading FK with an index.
  • A rateLimit table is created only when rateLimit.storage === "database".
  • Since 1.7.3, schema validation runs at startup by default — including production — and auth requests are rejected on a detected mismatch. A forgotten plugin migration now fails loudly at boot instead of silently at the first call.

7. Mount the route handler

app/api/auth/[...all]/route.ts:

TypeScript
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";

export const { GET, POST } = toNextJsHandler(auth);

8. Create the client

lib/auth-client.ts (full version with plugins: examples/auth-client.ts):

TypeScript
import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient();
export const { signIn, signUp, signOut, useSession } = authClient;

Import paths per framework: better-auth/react, /vue, /svelte, /solid, or vanilla better-auth/client.


Key patterns

Sign in and sign up

Every client method returns { data, error } — it does not throw.

TSX
"use client";
import { authClient } from "@/lib/auth-client";

async function onSubmit(email: string, password: string) {
  const { error } = await authClient.signIn.email({ email, password });
  if (error) return showError(error.message);
  router.push("/dashboard");
}
TypeScript
await authClient.signIn.social({ provider: "google", callbackURL: "/dashboard" });

Reading the session

Server (server component, route handler, server action) — authoritative:

TypeScript
import { headers } from "next/headers";
import { auth } from "@/lib/auth";

const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/sign-in");

Client — reactive hook: const { data: session, isPending } = authClient.useSession();

RSCs cannot set cookies, so the cookie cache is not refreshed until the client hits a server action or route handler.

Next.js 16: proxy.ts (formerly middleware)

Next.js 16 renames middleware.ts → proxy.ts and the export middleware → proxy. Run npx @next/codemod@canary middleware-to-proxy . or rename by hand; Better Auth helpers work unchanged. Full file: examples/proxy.ts.

TypeScript
// proxy.ts
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export function proxy(request: NextRequest) {
  const hasSession = getSessionCookie(request) !== null;
  if (!hasSession && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/sign-in", request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*"] };

This is a redirect optimisation, not an authorization boundary. getSessionCookie() checks presence, not validity — anyone can forge the cookie name. Re-check with auth.api.getSession() inside every protected page, action and handler.

Next 16's proxy runs on the Node.js runtime, so the docs also show calling auth.api.getSession({ headers: await headers() }) inside proxy() for a full DB-backed check. That costs a session lookup on every matched request; prefer the cookie check plus per-route validation unless the proxy genuinely needs the user. (Next 15.2–15.x needed runtime: "nodejs" in middleware config for the same thing; Next ≤15.1 Edge middleware cannot touch the DB at all.) If you changed advanced.cookiePrefix, pass { cookiePrefix } to getSessionCookie — it does not read your auth config.

TypeScript
session: {
  expiresIn: 60 * 60 * 24 * 7, // 7 days total lifetime
  updateAge: 60 * 60 * 24,     // slide the expiry at most once a day
  freshAge: 60 * 5,            // "recently authenticated" window for sensitive ops
  cookieCache: { enabled: true, maxAge: 5 * 60, strategy: "compact" }, // or "jwt" | "jwe"
}

cookieCache writes a separate session_data cookie so reads skip the database. A revoked session stays live on other devices until maxAge expires. Keep it short and leave it off wherever immediate revocation is required. Strategies: compact (default, signed, smallest), jwt (signed, readable), jwe (encrypted). Since 1.7 the cached session is bound to the session_token cookie. Other knobs: disableSessionRefresh, deferSessionRefresh, and fully stateless sessions (no database, cookieCache.strategy: "jwe", bump cookieCache.version to invalidate everyone).

Cookie defaults: HttpOnly, SameSite=Lax, Secure when the base URL is HTTPS or NODE_ENV is production (aligned with RFC 6265bis in 1.7.8).

Plugins

Plugins come in matched server + client pairs; schema-carrying ones need npx auth@latest generate and a migration.

PluginServer importClient import
organizationbetter-auth/pluginsbetter-auth/client/plugins → organizationClient
twoFactorbetter-auth/pluginstwoFactorClient
phoneNumberbetter-auth/pluginsphoneNumberClient
magicLink, emailOTP, admin, usernamebetter-auth/pluginsmatching *Client
passkey@better-auth/passkey@better-auth/passkey/client
stripe@better-auth/stripe@better-auth/stripe/client
SSO / SCIM / OAuth provider / MCP@better-auth/sso, @better-auth/scim, @better-auth/oauth-provider, @better-auth/mcpper package

Organization (multi-tenant)

TypeScript
organization({
  sendInvitationEmail: async (data) => {
    void sendEmail(data.email, `Join ${data.organization.name}`, `${baseUrl}/accept-invitation/${data.id}`);
  },
  // teams: { enabled: true },
})

Client: authClient.organization.create({ name, slug }), .setActive({ organizationId }), .inviteMember(...). Server permission checks: auth.api.hasPermission({ headers, body: { permissions: { project: ["create"] } } }). Custom roles use createAccessControl from better-auth/plugins/access, merged with defaultStatements from better-auth/plugins/organization/access. 1.7 added team.memberCount and teamMember.membershipKey columns — regenerate.

Two-factor

TypeScript
twoFactor({ otpOptions: { sendOTP: async ({ user, otp }) => { void sendEmail(user.email, "Code", otp); } } })

Set appName on betterAuth() — it becomes the TOTP issuer. 1.7 change: twoFactor.enable({ password, method }) takes method: "totp" | "otp" (default "totp") and returns a discriminated response — totpURI and backupCodes exist only when method === "totp". Enabling requires a password unless allowPasswordless: true (OAuth/passkey/phone-only users). 2FA is enforced only on /sign-in/email, /sign-in/username, /sign-in/phone-number; magic link, email OTP, social and passkey sign-ins skip it unless you add hooks. Client: twoFactorClient({ twoFactorPage: "/two-factor" }) or onTwoFactorRedirect({ twoFactorMethods }).

Passkey

TypeScript
import { passkey } from "@better-auth/passkey";
passkey({ rpName: "codeAmani App" }) // rpID / origin default from baseURL

Built on SimpleWebAuthn. authClient.passkey.addPasskey({ name }) (needs a session by default), authClient.signIn.passkey(). Passkey-first onboarding: registration: { requireSession: false, resolveUser } plus addPasskey({ context, createSession: true }).

Phone-number OTP (Kenya-targeted projects)

TypeScript
phoneNumber({
  otpLength: 6,
  expiresIn: 300,
  allowedAttempts: 3,                // default 3; then 403 "Too many attempts"
  requireVerification: true,
  phoneNumberValidator: (n) => /^\+254(7|1)\d{8}$/.test(n),
  sendOTP: ({ phoneNumber, code }) => {
    void sendSms(phoneNumber, `Your code is ${code}`); // don't await (timing); waitUntil on Vercel
  },
  signUpOnVerification: {
    getTempEmail: (n) => `${n.replace("+", "")}@phone.invalid`,
  },
})

Client: authClient.phoneNumber.sendOtp({ phoneNumber }) → authClient.phoneNumber.verify({ phoneNumber, code }). Other endpoints: signIn.phoneNumber({ phoneNumber, password }), phoneNumber.requestPasswordReset / resetPassword, verify({ ..., updatePhoneNumber: true }) to change numbers, updateUser({ phoneNumber: null }) to release one. Plug in an external verifier (e.g. Twilio Verify) with verifyOTP. Server-only auth.api.consumePhoneNumberOTP checks a code without creating a session. Normalisation helper: examples/phone.ts.

Stripe billing

Bash
npm install @better-auth/stripe@1.7.11 stripe@22.6.2
TypeScript
import { stripe } from "@better-auth/stripe";
import Stripe from "stripe";

stripe({
  stripeClient: new Stripe(process.env.STRIPE_SECRET_KEY as string),
  stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET as string, // required
  createCustomerOnSignUp: true,
  subscription: { enabled: true, plans: [{ name: "pro", priceId: process.env.STRIPE_PRO_PRICE_ID as string }] },
  organization: { enabled: true }, // REQUIRED since 1.7 for org-scoped subscriptions
})

Point a Stripe webhook at https://<domain>/api/auth/stripe/webhook; the plugin verifies the signature and handles checkout.session.completed and customer.subscription.created/updated/deleted, with onEvent for anything else. Org billing: authClient.subscription.upgrade({ plan, referenceId: org.id, customerType: "organization", seats }), guarded by subscription.authorizeReference. onSubscriptionCancel now always receives event.

Rate limiting

Enabled by default in production (10 s window, 100 requests). Runs before plugin hooks; returns 429. Server-side auth.api.* calls are never rate limited.

TypeScript
rateLimit: {
  enabled: true,
  storage: "database",           // or "secondary-storage" (Redis/Upstash)
  window: 60,
  max: 100,
  customRules: {
    "/sign-in/email": { window: 60, max: 5 },
    "/phone-number/send-otp": { window: 60, max: 3 },
  },
}

On Vercel, "memory" is per-instance and effectively useless. Behind Cloudflare, set advanced.ipAddress.ipAddressHeaders: ["cf-connecting-ip"]. Custom rate-limit stores now implement a single consume(key, rule) (1.7).

Database hooks

TypeScript
databaseHooks: {
  user: {
    create: {
      before: async (user) => (user.email.endsWith("@blocked.example") ? false : { data: user }),
      after: async (user) => { await provisionWorkspace(user.id); },
    },
  },
}

Returning false from a before hook aborts the operation. (1.8 beta makes this the supported way to reject sign-ups — don't throw from sendVerificationEmail.)


Breaking changes since the August review (1.7.1 → 1.7.11)

ReleaseChangeAction
1.7.0–1.7.2 → 1.7.31.7.0 added a required account.issuer column; 1.7.3 reverted it. Accounts are keyed by (providerId, accountId) again.If you migrated on 1.7.0–1.7.2: ALTER TABLE account ALTER COLUMN issuer DROP NOT NULL; DROP INDEX account_issuer_accountId_uidx; (Drizzle/Prisma: regenerate). Otherwise every sign-up fails.
1.7.3Startup schema validation on by default, rejects requests on mismatchRun npx auth@latest check schema in CI
1.7.3/oauth-proxy-callback deprecated (removed next minor)Move OAuth Proxy users off it before 1.8
1.7.5database.schemaName for direct Postgres; optional better-sqlite3 peer dropped—
1.7.6auth check / auth check schema commands; Vercel BotID captcha provider—
1.7.7Critical GHSA-965c-763c-88jm (OAuth state usable as a Magic Link → sign in as another user, >=1.4.0-beta.18 <1.7.7); high GHSA-r4xp-prcw-77qf (OAuth Proxy)Upgrade to ≥1.7.7; request fresh magic links; upgrade all servers sharing verification storage together
1.7.8Cookie attributes aligned with RFC 6265bis; password-reset OTPs no longer consumed on failed resets; phone-number resets honour verifyOTP—
1.7.11Fixed repeated Postgres int8 migration diffs; DB rate-limit X-Retry-After—

1.7.0 changes that still bite anyone coming from 1.6 (full list in the 1.7 upgrade guide): npx auth upgrade updates packages; the CLI needs Node 22.12; check for duplicate (providerId, accountId) rows first; experimental.joins → advanced.database.joins; twoFactor.enable returns { method, ... }; Stripe org subscriptions need organization.enabled; magic-link/email-OTP sign-in on an unverified account now wipes unproven passwords and sessions; captcha rules match full paths (/sign-in/*); secondary storage must implement increment + getAndDelete; getIp → getIP; generic OAuth now uses signIn.social and /api/auth/callback/:id; oidcProvider removed in favour of @better-auth/oauth-provider; MCP moved to @better-auth/mcp; Microsoft accounts key on oid, not sub.

On the horizon — 1.8 (beta): sign-up emails and OAuth session caching run after DB work completes (reject sign-ups via databaseHooks.user.create.before), device-authorization grant interface changes, new @better-auth/ciba package, FedCM account chooser for Google. Don't adopt until it reaches latest.


codeAmani notes

When to reach for Better Auth over Clerk

Clerk stays the default for codeAmani projects — hosted UI and zero ops win for most US-first SaaS. Reach for Better Auth when one of these holds:

  1. Auth data must join app data. Multi-tenant reporting, per-user analytics, and admin tooling get dramatically simpler when user is a real table next to your domain tables instead of a webhook-synced mirror.
  2. Per-MAU pricing breaks the model. The Kenya-targeted builds (duka-order-bot, boda-dispatch, sacco-chama-assistant) expect large low-ARPU user counts. A per-MAU bill in USD against KES revenue does not survive the spreadsheet; a Neon or Supabase row does.
  3. Phone-first identity. Many East African users have a reliable phone and no reliable email. The phoneNumber plugin with signUpOnVerification makes SMS OTP the primary credential. Store E.164 (+2547XXXXXXXX) in auth because SMS gateways want it, and convert to Daraja's 2547XXXXXXXX only at the M-Pesa boundary (toDarajaMsisdn in examples/phone.ts; rule in MPESA_PATTERNS.md). This replaces the earlier advice to validate ^254\d{9}$ in auth.
  4. SMS cost. Better Auth Infrastructure sells SMS at $0.09 per message on its $20/month Pro plan (see reference/limits-and-pricing.md). For Kenyan volumes, compare that against a local aggregator such as Africa's Talking before choosing; sendOTP lets you use either.

Security

  • Minimum version 1.7.7. Earlier 1.4–1.7 releases are exposed to a critical Magic Link account takeover. Pin exact versions and upgrade better-auth + every @better-auth/* package together (npx auth upgrade).
  • BETTER_AUTH_SECRET is server-side only. It signs cookies and encrypts stored OAuth tokens, so a leak is a session-forgery primitive. Never NEXT_PUBLIC_, never in a client component. Store it in Hazina; rotate with versioned BETTER_AUTH_SECRETS instead of a hard swap.
  • Never import lib/auth.ts from client code. It drags the DB driver, Stripe key and secret into the module graph. Client code imports lib/auth-client.ts only.
  • proxy.ts is not authorization. getSessionCookie() checks presence, not validity. Every protected server route and action re-checks with auth.api.getSession().
  • Secure the auth tables yourself. Better Auth connects directly to Postgres and bypasses PostgREST. On Supabase, put the tables in a non-exposed schema (e.g. better_auth, never auth) or enable RLS with no policies for anon/authenticated. account holds password hashes and OAuth refresh tokens; treat it as a secrets table.
  • Rate-limit credential and OTP routes with storage: "database" and tight customRules on /sign-in/email and /phone-number/send-otp — SMS pumping costs real money.
  • Webhook signatures still apply — to plugins. Better Auth has no inbound provider webhook of its own (unlike Clerk's Svix events). @better-auth/stripe receives real Stripe events at /api/auth/stripe/webhook and verifies them with stripeWebhookSecret (async constructEventAsync since stripe v19). Don't add a second, unverified Stripe route for the same events.
  • Email and SMS delivery are yours. Verification and reset links only exist if you send them. Wire sendVerificationEmail and sendResetPassword to Resend before enabling requireEmailVerification, or users get locked out silently.

AI routing

Better Auth has no AI surface of its own. If an agent or MCP server needs to act on behalf of a user, use the 1.7 @better-auth/oauth-provider + @better-auth/mcp packages rather than sharing session cookies; route model calls per AI_WORKFLOWS.md.

Ops

  • Pin versions; upgrade with npx auth upgrade (Node 22.12+ for the CLI).
  • After every plugin change: npx auth@latest generate, apply with your ORM, commit the migration, and run npx auth@latest check schema in CI. Startup validation will otherwise refuse requests in production.
  • Use a pooled connection string on Vercel; keep pg pool max small.
  • On serverless, consider advanced.backgroundTasks.handler: waitUntil (from @vercel/functions) so non-critical work runs after the response. The docs warn this introduces eventual consistency (optimistic responses before the DB write lands) — enable only where that is acceptable. For OTP/email sends, a void send(...) wrapped in waitUntil inside sendOTP is enough.