From knowledge-patch
Provides knowledge patches for Better Auth 1.6.0 covering authentication, OAuth, sessions, organizations, and more. Use when implementing or upgrading Better Auth.
How this skill is triggered — by the user, by Claude, or both
Slash command
/knowledge-patch:better-auth-knowledge-patchThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
Use this skill when implementing, upgrading, debugging, or reviewing Better Auth applications. Start with the quick references below, then load the topic file that matches the task.
agents/openai.yamlcoverage.jsonreferences/agent-auth.mdreferences/core-authentication.mdreferences/data-model-and-adapters.mdreferences/framework-integrations.mdreferences/identity-and-utility-plugins.mdreferences/infrastructure-and-observability.mdreferences/migration-guides.mdreferences/oauth-oidc-and-mcp.mdreferences/organizations-sso-and-scim.mdreferences/payments.mdreferences/plugin-development-and-testing.mdreferences/sessions-cookies-and-security.mdreferences/upgrades-and-cli.mdUse this skill when implementing, upgrading, debugging, or reviewing Better Auth applications. Start with the quick references below, then load the topic file that matches the task.
| Reference | Topics |
|---|---|
| agent-auth.md | Agent Auth discovery, JWT profiles, grants, approvals, execution, SDK, CLI, and hardening |
| core-authentication.md | Email/password, verification, account linking, social providers, usernames, and account deletion |
| data-model-and-adapters.md | IDs, schema generation, joins, hooks, official adapters, D1, Drizzle, Kysely, SQLite, and PostgreSQL |
| framework-integrations.md | Convex, Electron, Encore, Expo, Express, Lynx, NestJS, Next.js, SvelteKit, TanStack Start, Waku, and Workers |
| identity-and-utility-plugins.md | Two-factor, passkeys, OTP, magic links, phone, API keys, anonymous, bearer, JWT, SIWE, captcha, One Tap, and utility plugins |
| infrastructure-and-observability.md | Managed infrastructure, audit logs, Sentinel, email/SMS, OpenTelemetry, background tasks, and request-state diagnostics |
| migration-guides.md | Schema, package, endpoint, callback, hook, type, and plugin migrations |
| oauth-oidc-and-mcp.md | OAuth 2.1 provider, OIDC, generic OAuth, device authorization, resource servers, and MCP migration |
| organizations-sso-and-scim.md | Organizations, teams, dynamic roles, SSO, SAML, SCIM, provisioning, and domain trust |
| payments.md | Autumn, Stripe, Polar, Creem, Dodo Payments, and Openfort |
| plugin-development-and-testing.md | Middleware, plugin context, error codes, adapter predicates, lifecycle hooks, testing, and OpenAPI |
| sessions-cookies-and-security.md | Stateless auth, session placement, cookie cache, rate limits, CSRF/origin checks, secret rotation, and token storage |
| upgrades-and-cli.md | Standalone CLI, ESM, package alignment, release tracks, runtime compatibility, and removed exports |
Run the standalone executable instead of the old package-scoped CLI:
npx auth init
npx auth migrate
npx auth generate --adapter prisma
npx auth upgrade
The distribution is ESM-only. Convert CommonJS loading before upgrading.
Several features now have dedicated packages:
import { sso } from "@better-auth/sso";
import { scim } from "@better-auth/scim";
import { passkey } from "@better-auth/passkey";
import { apiKey } from "@better-auth/api-key";
import { oauthProvider } from "@better-auth/oauth-provider";
Redis-backed secondary storage is installed from @better-auth/redis-storage.
Database adapters also have @better-auth/*-adapter packages. Direct adapter imports paired with better-auth/minimal reduce the imported distribution.
Important schema changes include:
teamId with the teamMembers join table.userId to referenceId and add configId.redirectURLs to redirectUrls.await authClient.requestPasswordReset({ email }); // not forgotPassword
await auth.api.accountInfo({ query }); // GET/query, not POST/body
Use createAdapterFactory instead of createAdapter, afterEmailVerification instead of onEmailVerification, and permissions instead of the organization model's permission field. See the migration reference for removed endpoint, type, export, and callback details.
Database create.after, update.after, and delete.after hooks run after commit. Put atomic follow-up writes in the adapter operation or transaction, not in an after hook.
Omitting database enables stateless session management. Account data can be kept in a signed cookie, and token/account endpoints remain available:
const auth = betterAuth({
socialProviders: { google: { clientId, clientSecret } },
account: { storeAccountCookie: true },
});
When secondary storage is configured, sessions move there by default. Opt into database persistence with storeSessionInDatabase; use preserveSessionInDatabase to retain rows after revocation.
Session freshAge is measured from createdAt, not updatedAt. Refreshing cannot keep a session fresh indefinitely. Stateless cookie-cache maxAge is bounded by session expiresIn.
Put the newest key first and retain older keys for decryption:
secrets: [
{ version: 2, value: process.env.AUTH_SECRET_V2! },
{ version: 1, value: process.env.AUTH_SECRET_V1! },
]
CSRF and origin validation are independent controls. disableCSRFCheck disables only CSRF defense; disableOriginCheck also disables callback/redirect validation and retains broader legacy disabling behavior. Never trust forwarded host/protocol headers unless a front proxy strips attacker-supplied values.
Provider access and refresh tokens are plain by default. Prefer the built-in option:
account: { encryptOAuthTokens: true }
@better-auth/oauth-provider implements OAuth 2.1 and OIDC authorization-code, refresh-token, and client-credentials flows, plus discovery, dynamic registration, consent, introspection, revocation, JWT/JWKS, PKCE policy, and rate limits.
plugins: [
jwt(),
oauthProvider({ loginPage: "/sign-in", consentPage: "/consent" }),
]
Mount both well-known metadata handlers at the issuer. A separate API also needs protected-resource metadata and should validate access tokens with verifyAccessToken, a resource client, or introspection for opaque tokens.
Move authorization-server duties from the legacy built-in MCP plugin to @better-auth/oauth-provider. Separate MCP resource servers can verify tokens with createMcpAuthClient.
GET, POST, PUT, PATCH, and DELETE.hooks: {
before: createAuthMiddleware(async (ctx) => inspect(ctx.path)),
after: createAuthMiddleware(async (ctx) => inspect(ctx.context.returned)),
}
Plugin hooks remain matcher/handler entries. A plugin init() receives the live mutable auth context and may return context keys for other plugins.
runInBackground() schedules work after the response. runInBackgroundOrAwait() uses the configured background handler, but awaits when none exists. Connect serverless lifetime primitives through advanced.backgroundTasks.handler; expect eventual consistency when database writes are deferred.
express.json(); Express 5 needs a named wildcard.nextCookies() last when Server Actions call auth.api directly, and validate full sessions for protected Next.js routes.getCookie() manually for non-client requests.Agent Auth separates persistent hosts from runtime agents. Each agent has an Ed25519 key, an immutable delegated/autonomous mode, scoped grants, and short-lived single-use Agent JWTs. Discovery starts at /.well-known/agent-configuration; unsupported major protocol versions must stop the client.
Use @better-auth/agent-auth for registration, approval, grant enforcement, and execution. Run its migration, keep automatic default grants low-risk, use durable secondary storage for replay/JWKS caches in multi-instance deployments, and require fresh sessions or WebAuthn proof of presence for sensitive approvals.
advanced.database.generateId may delegate selected models to the database by returning false or undefined.mode: "insensitive".getSession.npx claudepluginhub nevaberry/nevaberry-plugins --plugin knowledge-patchBetter Auth in TypeScript — setting up the auth instance, picking adapters, wiring framework route handlers, configuring sessions and cookies, adding plugins (2FA, organization, admin, magicLink, JWT), or porting from NextAuth/Auth.js, Clerk, Auth0, or Supabase Auth. Covers Next.js, SvelteKit, Hono, Express, Nuxt, Astro, and React/Vue/Svelte clients. Trigger when writing, reviewing, or migrating Better Auth code — and even when the user doesn't explicitly mention Better Auth but is working on TypeScript authentication, session cookies, OAuth providers, or auth-library migration. Contains 42 rules organized by impact across 8 categories.
Implements Better Auth with 40+ OAuth providers, 20+ plugins, and all adapters/frameworks. Use for authentication, login, OAuth, 2FA, magic links, SSO, Stripe, SCIM, or session management.
Integrates Better Auth TypeScript authentication for Cloudflare D1 via Drizzle/Kysely, Next.js, Nuxt, and 15+ frameworks. Use for auth setup, D1 adapter errors, OAuth/2FA/RBAC.