Skip to content
Back to skills

Better Auth Knowledge Patch

ASecurity

Better Auth

  • 25 stars
  • 0 votes
  • 0 copies
  • 4 views
  • Added May 27, 2026
developmentjavascriptrustgojavareactnextjsnodenodejsexpresstesting

Works with

  • terminal
  • cli
  • api
  • mcp

Security analysis

A100/100

Pro scans all 14 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Nevaberry/nevaberry-plugins --skill better-auth-knowledge-patch --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Better Auth Knowledge Patch?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Better Auth Knowledge Patch
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/nevaberry-better-auth-knowledge-patch/badge)](https://www.skillsdirectory.com/skills/nevaberry-better-auth-knowledge-patch)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: better-auth-knowledge-patch
description: Better Auth
version: "1.6.0"
license: MIT
metadata:
  author: Nevaberry
---



# Better Auth compatibility

Load this skill when configuring, migrating, integrating, or debugging Better Auth.
Use the topic references for complete behavior, examples, and version-specific changes.

## Reference index

| Reference | Topics |
| --- | --- |
| [Migration guides](references/migration-guides.md) | Removed APIs, imports, configuration, API key schema, OIDC and MCP migration, account identity |
| [Upgrades and CLI](references/upgrades-and-cli.md) | CLI commands, schema checks, migrations, runtime compatibility, coordinated security upgrades |
| [Core authentication](references/core-authentication.md) | Email, passwords, social sign-in, account linking, profile mapping, client and server calls |
| [Sessions, cookies, and security](references/sessions-cookies-and-security.md) | Stateless sessions, caches, refresh, secondary storage, origins, CSRF, rate limits, secrets |
| [Data model and adapters](references/data-model-and-adapters.md) | IDs, fields, joins, database adapters, transactions, hooks, verification storage |
| [Framework integrations](references/framework-integrations.md) | Server frameworks, SSR, cookies, Electron, Expo, Convex, Workers |
| [Identity and utility plugins](references/identity-and-utility-plugins.md) | API keys, passkeys, 2FA, OTP, usernames, anonymous users, admin, CAPTCHA, JWTs, translations |
| [Organizations, SSO, and SCIM](references/organizations-sso-and-scim.md) | Membership, teams, roles, invitations, SAML, domain verification, provisioning, managed connections |
| [OAuth, OIDC, and MCP](references/oauth-oidc-and-mcp.md) | Authorization servers, clients, consent, resources, DPoP, device grants, discovery, CIMD |
| [Agent Auth](references/agent-auth.md) | Hosts, agents, approval, grants, JWTs, execution, SDK, CLI, MCP server |
| [Payments](references/payments.md) | Autumn, Stripe, Polar, Creem, Dodo Payments, Openfort |
| [Infrastructure and observability](references/infrastructure-and-observability.md) | Dashboard, Sentinel, managed email and SMS, telemetry, tracing, diagnostics |
| [Plugin development and testing](references/plugin-development-and-testing.md) | Middleware, hooks, shared context, errors, OpenAPI, test factories, browser and database tests |

## Breaking changes and deprecations

- The package is ESM-only. Use ESM imports for integrations that previously loaded it as CommonJS.
- Move `advanced.generateId` to `advanced.database.generateId`.
  Replace `advanced.database.useNumberId` with `advanced.database.generateId: "serial"`; use `"uuid"` for UUID primary keys.
- Replace `authClient.forgotPassword` with `authClient.requestPasswordReset`.
  Account information uses `GET /account-info` and server parameters in `auth.api.accountInfo({ query })`.
- Replace `user.changeEmail.sendChangeEmailVerification` with `emailVerification.sendVerificationEmail` for the new address.
  For approval from the current address first, enable `user.changeEmail.enabled` and provide `user.changeEmail.sendChangeEmailConfirmation`.
- Email OTP, Magic Link, Phone Number, and the affected Organization callbacks receive `ctx` instead of `request`.
  Read the request through `ctx.request`; the migration reference names each affected callback.
- Import `apiKey` from `@better-auth/api-key` and `apiKeyClient` from `@better-auth/api-key/client`.
  Rename `ApiKey.userId` to `referenceId`, add `configId` with default `"default"`, and supply `userId` or headers to server `updateApiKey` calls.
- API-key mock sessions are disabled by default. Enable `enableSessionForAPIKeys` if the application relies on user-owned key sessions.
- Import passkeys from `@better-auth/passkey`; replace `reactStartCookies()` with `tanstackStartCookies()` from `better-auth/tanstack-start`.
- Replace custom-adapter `createAdapter` with `createAdapterFactory` when upgrading to 1.5.
- The legacy OIDC Provider is deprecated in 1.6 and scheduled for removal in the next minor release.
  `@better-auth/oauth-provider` is its successor; the migration reference covers clients, secrets, consent, and retained tokens.
- Rename legacy OIDC `redirectURLs` to `redirectUrls` in code and the database.
  Bundled MCP migration moves authorize, token, and register calls from `/mcp/` to `/oauth2/`, and session checks to `/oauth2/introspect`.
- Replace deprecated `authClient.dodopayments.checkout()` with `checkoutSession()` and navigate to the returned URL.
- In 1.7.13, move Cloudflare `tokenEndpointAuthMethod` into `tokenEndpointAuth: { method }`; the deprecated option continues to work.

## Coordinated upgrades and write restrictions

- Upgrade directly installed scoped packages alongside core for the June security update.
  The upgrade reference preserves the distinct core, SSO, SCIM, and OAuth Provider patch requirements.
- When deploying 1.7.7, upgrade all servers sharing verification storage together, request fresh Magic Links, and restart pending OAuth and SAML sign-ins.
  Upgrade every OAuth Proxy participant together as well; the Magic Link patch uses the existing database schema.
- Before upgrading to 1.7.12, configure each ID-token provider's `clientId` with all participating app IDs.
  OIDC SSO also requires a configured client ID and ID tokens containing both `exp` and `iat`.
- In 1.7.16, sign-up and sign-in reject `phoneNumber`, and social profiles cannot populate an unverified number.
  Use phone verification for user-driven updates and add `set-phone` to custom admin access-control statements and roles.
- Sign-up and update-user requests cannot set `stripeCustomerId` starting in 1.7.16.
  Trusted server code that previously used `auth.api.updateUser` must write it through the database adapter.
- In 1.7.29, `createVerificationValue` and `updateVerificationByIdentifier` return `Promise<Verification | null>`.
  Guard against `null`; verification update hooks also run on secondary storage, and a veto suppresses the associated code, link, token, or challenge.

## CLI and database schemas

The standalone CLI supports interactive setup and schema generation without a full auth configuration:

```sh
npx auth init
npx auth generate --adapter drizzle
```

- For configuration discovery, export `auth` or a default instance from `auth.ts` in the root, `lib/`, or `utils/`, optionally under `src/`, `app/`, or `server/`.
- Use `npx auth@latest migrate` for built-in Kysely connections.
  For Prisma or Drizzle, use `npx auth@latest generate --output <path>` and apply the result with the ORM's migration tool.
- `npx auth@latest check` and `npx auth@latest check schema` validate without writing changes.
- Required columns without defaults cannot be added to populated tables by the CLI; supply a default or backfill in a staged migration.
- Kysely, Drizzle, and Prisma validate schemas during initialization by default in 1.7.3, including in production; detected mismatches block auth requests.
- Enable experimental joins with `experimental.joins: true`, then rerun migrations or regenerate the adapter schema.
  Drizzle needs relation definitions in its adapter schema; Prisma needs corresponding `@relation` definitions.
- Use `better-auth/minimal` with an adapter to omit Kysely from the server bundle; use the main entry point for direct database connections.
- CLI prompts go to stderr; missing input in CI or without a terminal exits with 2, cancellation with 130, and command failure with 1 from 1.7.19.

## Sessions, storage, and request security

- Omit `database` for stateless sessions. Social `getAccessToken()`, `accountInfo()`, and refresh-token requests also work without a database.
- `account.storeAccountCookie: true` stores account data in a cookie; account-cookie storage defaults to enabled without a database.
  Read its decrypted payload with `getAccountCookie(ctx)` from `better-auth/cookies`.
- For a database-backed cache, `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.
- For a current lookup, call `auth.api.getSession` with `query: { disableCookieCache: true }`.
- `secondaryStorage` moves sessions there by default. Set `session.storeSessionInDatabase: true` to persist them in both stores.
  `session.preserveSessionInDatabase: true` retains database records after revocation clears the secondary store.
- `session.freshAge` measures time from `createdAt`, so regular refreshes do not extend session freshness.
- Use `deferSessionRefresh` for read replicas. A GET can return `needsRefresh: true`, and the built-in client follows up with a POST.
- In stateless mode, cache `maxAge` follows `session.expiresIn`; `refreshCache: true` renews at roughly 20% remaining lifetime.
  Bump `session.cookieCache.version` to invalidate cookies issued under the previous version.
- Dynamic `baseURL.allowedHosts` entries also become trusted origins. Set an explicit cookie `domain` to share cookies between sibling hosts.
- `advanced.disableOriginCheck` also disables CSRF protection; `advanced.disableCSRFCheck` disables Fetch Metadata and cookie-origin checks.
- The built-in rate limiter covers HTTP requests handled by Better Auth. Apply required limits separately for direct `auth.api` calls in custom routes.
- Put new versioned `secrets` first for writes and retain old keys for decryption.
  Keep the singular `secret` as a fallback while legacy ciphertext still needs it.

## Hooks, fields, and client responses

- Database after hooks run after commit. Additional writes that must commit atomically belong inside the main operation.
  On adapters without transactions, after hooks run for retained writes even if the request fails from 1.7.8.
- `databaseHooks` covers `user`, `session`, and `account`; a before hook can replace data, return `false` to cancel, or throw `APIError` for a specific failure.
- Physical table and column mappings do not change API or hook field names. Additional-field defaults run in JavaScript and leave database columns optional.
  Use `input: false` for fields clients should never set; use `inferAdditionalFields<typeof auth>()` for client inference.
- Pass `returnHeaders: true` for `{ headers, response }`, or `asResponse: true` for a Fetch `Response`.
- As of 1.7.21, a thrown `sendVerificationEmail` error is logged and sign-up succeeds.
  Enforce sign-up rejection in `databaseHooks.user.create.before`.
- Use `APIError.from` with `defineErrorCodes` entries to preserve machine-readable error codes.
  Server-side error causes stay out of HTTP responses in 1.7.12.

## OAuth, OIDC, and MCP

- Register `jwt()` and `oauthProvider({ loginPage, consentPage })` for the OAuth Provider.
  It supports authorization-code, refresh-token, and client-credentials grants, dynamic registration, introspection, revocation, and remote JWT verification.
- Mount authorization-server and OpenID discovery at the paths specified in the OAuth reference for the configured issuer.
- Use `clientPrivileges` for client CRUD policy; `clientId` identifies the targeted existing client from 1.7.8.
  Restricted fields use server-only `adminCreateOAuthClient` and `adminUpdateOAuthClient`.
- Verify signed authorization queries with `verifyOAuthQueryParams` before rendering a custom consent page.
  Resume tenant selection with `oauth2Continue({ postLogin: true })`; `isContinuation` can prevent repeated organization selection.
- Request an allowed `resource` for a JWT access token and verify its issuer, audience, and scopes with `verifyAccessToken`.
  With `disableJwtPlugin: true`, access tokens are opaque and use introspection.
- Routes protected by `requireMcpAuth` require OAuth access tokens from 1.7.12; session JWTs fail even with matching issuer and audience.
- For custom DPoP endpoints, use `requireActiveAccessToken` and `enforceDpopBinding` with the request and a shared replay store.
  Multi-instance MCP handlers can use `dpop: { replayStore: createDpopReplayStore(internalAdapter) }`.
- Include `WWW-Authenticate` in `Access-Control-Expose-Headers` if the CORS layer sets that header.
- In 1.7.27, refresh tokens issued without `offline_access` stop working when their session expires or is deleted.

## Organizations, SSO, and SCIM

- Migrate old `member.teamId` associations to `teamMembers` before dropping the column; members can belong to multiple teams.
- Organization creation with session headers makes the caller the creator regardless of `body.userId`.
  Omit those headers when trusted server code creates an organization for another user.
- A function supplied as `organizationLimit(user)` returns true when creation should be blocked because the cap is reached.
- Merge built-in role statements when extending permissions. Runtime roles require `dynamicAccessControl.enabled`, a server `ac`, and the `organizationRole` migration.
- Install SSO from `@better-auth/sso`. Domain verification uses a TXT record at `_better-auth-token-<providerId>` and `/sso/verify-domain`.
- SAML request correlation validates `InResponseTo` by default; `wantAssertionsSigned` requires signatures on the assertions themselves.
- Register `scim()` from `@better-auth/scim` for provisioning; `managedConnections` supports runtime tenant connections and server-only credential management.
- In 1.7.21, SCIM can start on adapters without native transactions, but `/scim/v2` returns 501 there; provisioning needs native transactions.

## Framework and runtime integration

- In Express 5, mount `app.all("/api/auth/{*any}", toNodeHandler(auth))` before `express.json()`.
- SvelteKit requires explicit `building` and `getRequestEvent`; put `sveltekitCookies(getRequestEvent)` last in the plugins.
- TanStack Start with Solid imports cookies from `better-auth/tanstack-start/solid` and registers the helper last.
- For Expo session polling, run `npx expo install expo-network`; native protected fetches must pass the stored cookie explicitly.
- Electron uses the system browser through `requestAuth()`; preserve the callback's PKCE and state fields and match desktop/web plugin configuration.
- Cloudflare Workers need AsyncLocalStorage: use `nodejs_compat` with compatibility date `2024-09-23` or later, or `nodejs_als` for AsyncLocalStorage alone.
- Next.js optimistic cookie checks need custom `cookieName` and `cookiePrefix`; validate sessions inside protected pages and actions with `auth.api.getSession`.

## Identity plugins and Agent Auth

- For passkey-first onboarding, set `registration.requireSession` to `false`.
  In `registration.resolveUser`, validate the onboarding context, create or load the user, and return `id` and `name`.
  Pass the same opaque `context` to `addPasskey` during verification.
- Two-factor passwordless enrollment uses `allowPasswordless: true`; server-side 2FA continuation needs the sign-in response cookies.
- API key named configurations use `configId`; administering organization-owned keys requires organization membership and the appropriate `apiKey` permission.
  Key `expiresIn` uses seconds, default expiration uses milliseconds, and minimum/maximum expiration use days.
- Install `@better-auth/agent-auth`, register `agentAuth()`, and migrate its host, agent, grant, and approval tables.
  Agent modes are immutable; claiming an autonomous agent is terminal and continuing requires a new delegated agent.
- Sign fresh Agent JWTs per request. A custom capability location is an audience only for a token naming that single capability.
- Share replay and JWKS caches through secondary storage across replicas.
  In custom routes, use the returned `agent`, `host`, and linked `user` to enforce the route's capability requirements before acting.
- The Agent Auth reference covers approval polling, constrained grants, async and streaming execution, `@auth/agent`, and `auth-agent`.

## Payments, testing, and observability

- Stripe organization seat billing uses `organization.enabled` and plan `seatPriceId`; membership changes sync seat quantity with the organization plugin registered.
  Check membership and billing permissions in `subscription.authorizeReference`, including subscription listing.
- For an active Stripe subscription upgrade, pass its current Stripe `subscriptionId`; keep `referenceId` non-unique to allow resubscription after cancellation.
- Autumn checks entitlements on the server with `auth.api.check` and meters successful operations with `auth.api.track`.
  The payments reference preserves each provider's customer identity, checkout, webhook, and access-check contracts.
- Register `testUtils` and access `(await auth.$context).test` for factories and authenticated requests.
  OTP capture keeps a copy and still calls the delivery callback.
- OpenTelemetry endpoint, database, and hook spans are experimental and use the `better-auth` tracer.
  Register a tracer provider at startup; library telemetry is separately off by default and uses `telemetry.enabled` to opt in.

Files in this skill

  • SKILL.md9.6 KB
  • references/agent-auth.md7.9 KB
  • references/api-keys-and-billing.md5.7 KB
  • references/authentication.md7.4 KB
  • references/breaking-changes.md4.5 KB
  • references/configuration.md3.7 KB
  • references/core-plugins.md7.7 KB
  • references/database-adapters.md5.3 KB
  • references/framework-integrations.md9.2 KB
  • references/infrastructure.md4.7 KB
  • references/oauth-provider.md5 KB
  • references/organization.md2.8 KB
  • references/plugin-creation.md2.9 KB
  • references/sessions-and-hooks.md5.7 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.