Better Auth Integration Guide

Technology: better-auth · Category: auth · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/better-auth

Insight:

Better Auth is the self-hosted counterweight to Clerk — the user, session, account and verification tables live in your Postgres, so auth data joins directly against app data and there is no per-MAU bill. You trade a managed dashboard for full ownership: you run the migrations, you secure the tables, you send the emails and the SMS. Run 1.7.7 or later — 1.7.7 patched a critical Magic Link account takeover — and pin every @better-auth/* package to the same version.

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

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 / Auth0 Better Auth
User data lives in the vendor's database your Postgres (user, session, account, verification)
Joining users to app data webhook-synced mirror table a plain SQL JOIN
Pricing per monthly-active-user your database bill (framework is free, MIT)
Pre-built UI hosted components you build the forms
Email / SMS delivery included you wire it (Resend, Africa's Talking) — or pay for Better Auth Infrastructure
Ops burden none migrations, secret rotation, table security
flowchart LR
  A["Browser<br/>authClient"] -->|"fetch /api/auth/*"| B["Catch-all route<br/>toNextJsHandler(auth)"]
  P["proxy.ts<br/>getSessionCookie()"] -.->|"optimistic redirect"| A
  B --> C["betterAuth() instance<br/>lib/auth.ts"]
  C --> D["Adapter<br/>drizzle · prisma · pg (Kysely)"]
  D --> E[("Your Postgres<br/>Neon · Supabase<br/>user · session · account · verification")]
  C --> F["Plugins<br/>organization · twoFactor<br/>phoneNumber · passkey · stripe"]
  B -.->|"Set-Cookie<br/>HttpOnly · Secure · SameSite=Lax"| A

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

Package Version Notes
better-auth 1.7.11 (latest) 1.8.0-beta.1 is on the beta tag — not for production
auth (CLI) 1.7.11 requires Node ≥ 22.12
@better-auth/drizzle-adapter, @better-auth/prisma-adapter 1.7.11 split out of core; still re-exported as better-auth/adapters/*
@better-auth/passkey, @better-auth/stripe 1.7.11 upgrade 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 || ^16 Next 16.4.2 current
drizzle-orm peer range ^0.45.2 || >=1.0.0-rc.1 <2
prisma / @prisma/client peer range ^5 || ^6 || ^7 Prisma 8 is still RC

Official Documentation

Resource URL
Docs home https://better-auth.com/docs
Installation https://better-auth.com/docs/installation
Next.js integration (proxy.ts) https://better-auth.com/docs/integrations/next
Database & adapters https://better-auth.com/docs/concepts/database
Session management https://better-auth.com/docs/concepts/session-management
CLI https://better-auth.com/docs/concepts/cli
1.7 upgrade guide https://better-auth.com/docs/guides/1-7-upgrade-guide
Source & releases https://github.com/better-auth/better-auth

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

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:

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_*):

# .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:

Variable Example Purpose
BETTER_AUTH_URL http://localhost:3000 Base URL Better Auth builds callback URLs from
NEXT_PUBLIC_APP_URL https://app.example.com Client baseURL — only needed when auth runs on another origin
GOOGLE_CLIENT_ID 1234-abc.apps.googleusercontent.com OAuth client ID (public by design)
STRIPE_PRO_PRICE_ID price_... 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.

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)

Option Import Migrations
Raw pg Pool (built-in Kysely) new Pool({ connectionString }) passed as database npx auth@latest migrate applies them
Drizzle drizzleAdapter from @better-auth/drizzle-adapter (Relations v2: @better-auth/drizzle-adapter/relations-v2) npx auth@latest generate → drizzle-kit generate → drizzle-kit migrate
Prisma 7 prismaAdapter from better-auth/adapters/prisma (package: @better-auth/prisma-adapter) npx auth@latest generate → prisma migrate dev
// 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" })

6. Create the tables

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:

7. Mount the route handler

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

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):

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.

"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");
}
await authClient.signIn.social({ provider: "google", callbackURL: "/dashboard" });

Reading the session

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

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.

// 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.

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.

Plugin Server import Client import
organization better-auth/plugins better-auth/client/plugins → organizationClient
twoFactor better-auth/plugins twoFactorClient
phoneNumber better-auth/plugins phoneNumberClient
magicLink, emailOTP, admin, username better-auth/plugins matching *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/mcp per package

Organization (multi-tenant)

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

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

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)

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

npm install @better-auth/stripe@1.7.11 stripe@22.6.2
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.

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

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)

Release Change Action
1.7.0–1.7.2 → 1.7.3 1.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.3 Startup schema validation on by default, rejects requests on mismatch Run 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.5 database.schemaName for direct Postgres; optional better-sqlite3 peer dropped —
1.7.6 auth check / auth check schema commands; Vercel BotID captcha provider —
1.7.7 Critical 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.8 Cookie attributes aligned with RFC 6265bis; password-reset OTPs no longer consumed on failed resets; phone-number resets honour verifyOTP —
1.7.11 Fixed 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

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

Official docs: