Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Better Auth Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-better-auth-knowledge-patch-nevaberry-plugins)
---
name: better-auth-knowledge-patch
description: Better Auth
version: "1.6.0"
license: MIT
metadata:
author: Nevaberry
---
# Better Auth Knowledge Patch
Use this skill when implementing, upgrading, or debugging Better Auth authentication,
database adapters, plugins, or framework integrations. Load the topic reference for
the task; the quick references below emphasize migration requirements and common flows.
## Reference index
| Reference | Topics |
| --- | --- |
| [Migration guides](references/migration-guides.md) | Moved imports, renamed APIs, account and API-key schemas, OIDC and MCP migrations |
| [Upgrades and CLI](references/upgrades-and-cli.md) | Security upgrades, schema generation, migrations, diagnostics, dependency compatibility |
| [Core authentication](references/core-authentication.md) | Email, passwords, account deletion, social providers, linking, Generic OAuth |
| [Sessions, cookies, and security](references/sessions-cookies-and-security.md) | Stateless sessions, caches, refresh, revocation, dynamic hosts, origins, rate limits, secrets |
| [Data model and adapters](references/data-model-and-adapters.md) | Schema mapping, IDs, additional fields, experimental joins, Redis, SQL, MongoDB, D1 |
| [Framework integrations](references/framework-integrations.md) | SvelteKit, TanStack Start, Expo, Electron, Convex, Next.js, Express, Fastify, Hono, and other runtimes |
| [Identity and utility plugins](references/identity-and-utility-plugins.md) | API keys, passkeys, two-factor authentication, OTP, admin, anonymous users, JWT, CAPTCHA, translations |
| [Organizations, SSO, and SCIM](references/organizations-sso-and-scim.md) | Membership, invitations, roles, teams, provider management, SAML, provisioning |
| [OAuth, OIDC, and MCP](references/oauth-oidc-and-mcp.md) | Authorization server, clients, consent, resources, DPoP, device flow, CIMD, legacy integrations |
| [Agent Auth](references/agent-auth.md) | Host and agent identity, approval, capabilities, grants, SDK, CLI, resource servers |
| [Payments](references/payments.md) | Stripe, Autumn, Polar, Creem, Dodo Payments, Openfort |
| [Plugin development and testing](references/plugin-development-and-testing.md) | Hooks, middleware, context, errors, schemas, inference, test helpers, OpenAPI |
| [Infrastructure and observability](references/infrastructure-and-observability.md) | Dashboard, Sentinel, managed email and SMS, telemetry, experimental tracing |
## Breaking changes and deprecations
Use ESM imports; the package is ESM-only. Move SSO, passkey, and API-key imports to
`@better-auth/sso`, `@better-auth/passkey`, and `@better-auth/api-key` respectively.
Import the API-key client from `@better-auth/api-key/client`.
The legacy OIDC Provider is deprecated in 1.6 and scheduled for removal in the next
minor release. Its successor is `@better-auth/oauth-provider`. The migration reference
contains client, consent, secret, and token-table transformations.
For bundled MCP migration, move authorize, token, and register calls from `/mcp/`
to `/oauth2/`, and replace `/mcp/get-session` with `/oauth2/introspect`.
Starting in 1.7.12, `requireMcpAuth` requires an OAuth access token; a session JWT
fails even when issuer and audience match.
| Existing integration | Required change |
| --- | --- |
| `advanced.generateId` | Move to `advanced.database.generateId`. |
| `advanced.database.useNumberId` | Use `advanced.database.generateId: "serial"`. |
| `authClient.forgotPassword` | Use `authClient.requestPasswordReset`. |
| `user.changeEmail.sendChangeEmailVerification` | Use `emailVerification.sendVerificationEmail` for the new address. |
| OIDC `redirectURLs` | Rename to `redirectUrls` in code and migrate the database field. |
| Custom adapter `createAdapter` | Replace with `createAdapterFactory` when upgrading to 1.5. |
| `reactStartCookies()` from `better-auth/react-start` | Use `tanstackStartCookies()` from `better-auth/tanstack-start`. |
| `getMigrations` imports | Import from `better-auth/db/migration`. |
Migrate API-key `userId` to `referenceId` and add `configId` with default `"default"`.
`permissions.defaultPermissions` now receives `referenceId` as its first argument.
Server calls to `updateApiKey` must include `userId` or request headers.
Move organization `member.teamId` associations to `teamMembers` before dropping the
column. Use `maximumMembersPerTeam` for per-team caps.
As of 1.7.3, accounts use `(providerId, accountId)`. Upgrades from 1.6 can reuse the
account schema; installations of the issuer schema from 1.7.0–1.7.2 need cleanup
without an account-data backfill.
Before upgrading to 1.7.12, configure provider `clientId` with all app IDs used for
ID-token sign-in. OIDC SSO also needs a client ID and ID tokens with `exp` and `iat`.
Upgrade to 1.7.7 together on servers sharing verification storage, request fresh
Magic Links, and restart pending OAuth and SAML sign-ins. Upgrade every OAuth Proxy
participant together too. See the upgrade reference for security package targets.
## CLI and database changes
Use `npx auth init` to scaffold configuration, an adapter, and framework integration.
`npx auth generate --adapter drizzle` can generate without a full auth configuration.
For built-in Kysely connections, `npx auth@latest migrate` applies schema changes.
For Prisma and Drizzle, use `npx auth@latest generate --output <path>` and apply the
result through the ORM's migration tool. Run `npx auth@latest check` or
`npx auth@latest check schema` for read-only schema validation, available in 1.7.6.
The CLI refuses a required column without a default on a populated table. Supply a
default or backfill in a staged migration before making it required.
In 1.7.3, Kysely, Drizzle, and Prisma validate schemas at initialization by default,
including production; detected mismatches block auth requests.
Use `better-auth/minimal` with adapters such as Prisma, Drizzle, or MongoDB to omit
Kysely. Use the main entry point for direct database connections.
Standalone adapter packages remain re-exported by the main package.
`experimental.joins: true` requires rerunning migrations or regenerating the schema.
Include relation definitions in Drizzle's `schema`; Prisma needs matching `@relation`
definitions. MongoDB transactions require the originating `MongoClient` in adapter options.
D1 accepts `database: env.DB` and uses batches for atomic operations. As of 1.7.21,
SCIM can coexist with an adapter without native transactions at startup, but
`/scim/v2` returns 501 there; provisioning requires native transactions.
## Sessions, cookies, and request boundaries
Omit `database` for stateless authentication. Use `account.storeAccountCookie: true`
to retain account data in a cookie; account-cookie storage defaults on without a database.
The stateless session cache uses `session.expiresIn` as its `maxAge`.
For database-backed caches, `session.cookieCache.strategy` defaults to `"compact"`. The documented automatic no-database configuration uses `"jwe"`; set the strategy explicitly when confidentiality matters.
`"compact"` and `"jwt"` are signed and readable; `"jwe"` encrypts the payload.
Revoked sessions can appear active until the cache expires. Use
`query: { disableCookieCache: true }` on `auth.api.getSession` for a current lookup.
`secondaryStorage` moves sessions there by default. `session.storeSessionInDatabase`
also persists them in the database; `session.preserveSessionInDatabase` retains
database records after revocation clears the secondary store.
`session.freshAge` measures from `createdAt`, so regular refreshes do not keep a
session fresh. Deferred refresh returns `needsRefresh: true` from `GET /get-session`;
the built-in client follows up with a POST.
Dynamic `baseURL` accepts `allowedHosts`, `fallback`, and `protocol: "auto"`.
Allowed hosts also become trusted origins. With automatic protocol selection,
cookie security follows `NODE_ENV === "production"`; override with `advanced.useSecureCookies`.
Only enable `advanced.trustedProxyHeaders` behind a proxy controlling both forwarded headers.
The built-in limiter covers HTTP requests, so apply any required limits separately
for direct `auth.api` calls. Sign-in/sign-up default to three requests per 10 seconds;
password reset and OTP default to three per 60 seconds. Use shared storage for shared counters.
For secret rotation, put the new `{ version, value }` first in `secrets` and retain
old entries for decryption. Keep the previous singular `secret` while legacy
ciphertext still needs that fallback.
## Authentication and identity plugins
Required email verification conceals existing accounts during sign-up, and
`emailAndPassword.autoSignIn: false` also enables indistinguishable duplicate responses.
Use `customSyntheticUser` for plugin fields. Enumeration-protected `/change-email`
returns `{ status: true }`, which cannot confirm message delivery.
In 1.7.21, a thrown `sendVerificationEmail` error is logged while sign-up succeeds.
Enforce rejection conditions in `databaseHooks.user.create.before`.
Use server-side `verifyPassword` to check the signed-in user's password before a
sensitive operation.
API-key sessions are disabled by default. `enableSessionForAPIKeys` only supports
user-owned keys; calling both `verifyApiKey` and key-backed `getSession` counts twice
against the key's rate limit. Named key configurations need the matching `configId`.
For passkey-first onboarding, set `registration.requireSession: false`, validate the
onboarding context in `registration.resolveUser`, and return the user's `id` and `name`.
Pass the same opaque `context` to `passkey.addPasskey`. Inspect returned errors even
with `throw: true`. Wildcard hosts covering `rpID` need explicit or exact trusted
origins in 1.7.21; tenant callbacks should check tenant records.
`twoFactor({ allowPasswordless: true })` enables passwordless accounts to manage 2FA.
Server-side two-factor continuation needs cookies from the sign-in response forwarded
to the next call. Email OTP, phone OTP, and magic-link storage and attempt settings
have distinct contracts; the identity reference preserves their units and defaults.
## Organizations, SSO, OAuth, and agents
Overriding built-in organization roles replaces permissions. Merge the built-in
statements to retain them. Dynamic roles require `dynamicAccessControl.enabled` on
both plugins, a server `ac`, and migration of `organizationRole`.
For organization creation on another user's behalf, use `body.userId` without
session headers. With headers, the caller becomes the creator regardless of `userId`.
`organizationLimit(user)` returning true means the cap has been reached.
SAML sign-in validates `InResponseTo` by default. `wantAssertionsSigned` requires
signatures on assertions themselves. SCIM connection-management endpoints require
authenticated, authorized callers; managed connections expose server-only credential operations.
The OAuth Provider supports authorization-code, refresh-token, and client-credentials
grants. A permitted `resource` requests a JWT access token; `disableJwtPlugin: true`
instead produces opaque access tokens checked through `/oauth2/introspect`.
For custom DPoP endpoints, use `requireActiveAccessToken` and `enforceDpopBinding`
with a shared replay store. Session-bound refresh tokens without `offline_access`
stop working when their session expires or is deleted in 1.7.27.
Agent Auth uses separate Host and Agent JWTs. Execution uses the capability's
`location` or provider `default_location` as URL and audience; capability-specific
audiences require a claim naming that single capability. Use a fresh JWT per request,
shared replay storage across replicas, and enforce route capabilities before acting.
## Hooks, framework integration, and testing
Use `createAuthMiddleware` for endpoint hooks. Database after hooks run after commit;
additional writes that must commit atomically belong inside the main operation.
Plugin HTTP middleware does not cover direct `auth.api` calls: put required checks
in the endpoint or its endpoint middleware.
Pass `returnHeaders: true` to receive `{ headers, response }`, or `asResponse: true`
for a Fetch `Response`. SvelteKit needs explicit `building` and `getRequestEvent`
inputs; its server-action cookie plugin goes last. Express 5 needs a named wildcard
auth route before `express.json()`. Consult the framework reference for each runtime.
Register `testUtils` and use `(await auth.$context).test` for users, sessions, and
authenticated request headers. `captureOTP: true` enables `test.getOTP(email)`;
capture still calls the delivery callback. Use `test.getCookies` for browser tests.
## Payments and observability
Stripe organization billing uses `organization.enabled`, a plan's `seatPriceId`, and
the organization plugin for membership-driven seat updates. Implement
`subscription.authorizeReference` for organization billing permissions, including lists.
For an active subscription change, pass its Stripe `subscriptionId` to avoid a second
subscription. Keep `referenceId` non-unique to permit resubscription after cancellation.
The payments reference includes provider-specific entitlement checks, webhook setup,
checkout redirects, and persistence modes. With Autumn, check limits on the server
with `auth.api.check` and meter successful usage through `auth.api.track`.
Library telemetry is off by default. Register an OpenTelemetry tracer provider to
enable experimental endpoint, database, and hook spans. Use `better_auth.operation_id`
to group spans. In 1.7.4, disable spans for one instance with
`betterAuth({ experimental: { instrumentation: { enabled: false } } })`.
The 1.6 line gained per-instance span control in 1.6.31.