[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6PXZXG0MWS3WFTSKZJQMNAK":3,"skill-same:01M6PXZXG0MWS3WFTSKZJQMNAK":135},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":6,"ownerHtmlUrl":57,"ownerBlogUrl":6,"ownerDescription":58,"updatedAt":59,"install":60,"resources":72},"01M6PXZXG0MWS3WFTSKZJQMNAK","better-auth",null,"Self-hosted auth for TypeScript\u002FCloudflare Workers with social auth, 2FA, passkeys, organizations, RBAC, and 15+ plugins. Requires Drizzle ORM or Kysely for D1 (no direct adapter). Self-hosted alternative to Clerk\u002FAuth.js.\n\nUse when: self-hosting auth on D1, building OAuth provider, multi-tenant SaaS, or troubleshooting D1 adapter errors, session caching, rate limits, Expo crashes, additionalFields bugs.","Kernel8901\u002Fai-agent-skills-classification","Kernel8901","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F72647553?v=4","01M6KV388J2H5PNC8D8P940BJD","01M6KV38CS5B3AY63RKZB410YM",7,"MIT","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"auth","better auth","clerk","limits","rate","oauth provider","tenant","d1","for","kysely","expo","rbac","typescript","self-hosted","cloudflare workers","edit","write","read","drizzle orm","passkeys","2026-11-10 10:12:30",false,"---\nname: better-auth\ndescription: |\n  Self-hosted auth for TypeScript\u002FCloudflare Workers with social auth, 2FA, passkeys, organizations, RBAC, and 15+ plugins. Requires Drizzle ORM or Kysely for D1 (no direct adapter). Self-hosted alternative to Clerk\u002FAuth.js.\n\n  Use when: self-hosting auth on D1, building OAuth provider, multi-tenant SaaS, or troubleshooting D1 adapter errors, session caching, rate limits, Expo crashes, additionalFields bugs.\nuser-invocable: true\nallowed-tools:\n  - Read\n  - Write\n  - Edit\n  - Bash\n  - Glob\n  - Grep\n---\n\n# better-auth - D1 Adapter & Error Prevention Guide\n\n**Package**: better-auth@1.4.16 (Jan 21, 2026)\n**Breaking Changes**: ESM-only (v1.4.0), Admin impersonation prevention default (v1.4.6), Multi-team table changes (v1.3), D1 requires Drizzle\u002FKysely (no direct adapter)\n\n---\n\n## ⚠️ CRITICAL: D1 Adapter Requirement\n\nbetter-auth **DOES NOT** have `d1Adapter()`. You **MUST** use:\n- **Drizzle ORM** (recommended): `drizzleAdapter(db, { provider: \"sqlite\" })`\n- **Kysely**: `new Kysely({ dialect: new D1Dialect({ database: env.DB }) })`\n\nSee Issue #1 below for details.\n\n---\n\n## What's New in v1.4.10 (Dec 31, 2025)\n\n**Major Features:**\n- **OAuth 2.1 Provider plugin** - Build your own OAuth provider (replaces MCP plugin)\n- **Patreon OAuth provider** - Social sign-in with Patreon\n- **Kick OAuth provider** - With refresh token support\n- **Vercel OAuth provider** - Sign in with Vercel\n- **Global `backgroundTasks` config** - Deferred actions for better performance\n- **Form data support** - Email authentication with fetch metadata fallback\n- **Stripe enhancements** - Flexible subscription lifecycle, `disableRedirect` option\n\n**Admin Plugin Updates:**\n- ⚠️ **Breaking**: Impersonation of admins disabled by default (v1.4.6)\n- Support role with permission-based user updates\n- Role type inference improvements\n\n**Security Fixes:**\n- SAML XML parser hardening with configurable size constraints\n- SAML assertion timestamp validation with per-provider clock skew\n- SSO domain-verified provider trust\n- Deprecated algorithm rejection\n- Line nonce enforcement\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fchangelogs\n\n---\n\n## What's New in v1.4.0 (Nov 22, 2025)\n\n**Major Features:**\n- **Stateless session management** - Sessions without database storage\n- **ESM-only package** ⚠️ Breaking: CommonJS no longer supported\n- **JWT key rotation** - Automatic key rotation for enhanced security\n- **SCIM provisioning** - Enterprise user provisioning protocol\n- **@standard-schema\u002Fspec** - Replaces ZodType for validation\n- **CaptchaFox integration** - Built-in CAPTCHA support\n- Automatic server-side IP detection\n- Cookie-based account data storage\n- Multiple passkey origins support\n- RP-Initiated Logout endpoint (OIDC)\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fchangelogs\n\n---\n\n## What's New in v1.3 (July 2025)\n\n**Major Features:**\n- **SSO with SAML 2.0** - Enterprise single sign-on (moved to separate `@better-auth\u002Fsso` package)\n- **Multi-team support** ⚠️ Breaking: `teamId` removed from member table, new `teamMembers` table required\n- **Additional fields** - Custom fields for organization\u002Fmember\u002Finvitation models\n- Performance improvements and bug fixes\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fblog\u002F1-3\n\n---\n\n## Alternative: Kysely Adapter Pattern\n\nIf you prefer Kysely over Drizzle:\n\n**File**: `src\u002Fauth.ts`\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { Kysely, CamelCasePlugin } from \"kysely\";\nimport { D1Dialect } from \"kysely-d1\";\n\ntype Env = {\n  DB: D1Database;\n  BETTER_AUTH_SECRET: string;\n  \u002F\u002F ... other env vars\n};\n\nexport function createAuth(env: Env) {\n  return betterAuth({\n    secret: env.BETTER_AUTH_SECRET,\n\n    \u002F\u002F Kysely with D1Dialect\n    database: {\n      db: new Kysely({\n        dialect: new D1Dialect({\n          database: env.DB,\n        }),\n        plugins: [\n          \u002F\u002F CRITICAL: Required if using Drizzle schema with snake_case\n          new CamelCasePlugin(),\n        ],\n      }),\n      type: \"sqlite\",\n    },\n\n    emailAndPassword: {\n      enabled: true,\n    },\n\n    \u002F\u002F ... other config\n  });\n}\n```\n\n**Why CamelCasePlugin?**\n\nIf your Drizzle schema uses `snake_case` column names (e.g., `email_verified`), but better-auth expects `camelCase` (e.g., `emailVerified`), the `CamelCasePlugin` automatically converts between the two.\n\n**⚠️ Cloudflare Workers Note**: D1 database bindings are only available inside the request handler (the `fetch()` function). You cannot initialize better-auth outside the request context. Use a factory function pattern:\n\n```typescript\n\u002F\u002F ❌ WRONG - DB binding not available outside request\nconst db = drizzle(env.DB, { schema }) \u002F\u002F env.DB doesn't exist here\nexport const auth = betterAuth({ database: drizzleAdapter(db, { provider: \"sqlite\" }) })\n\n\u002F\u002F ✅ CORRECT - Create auth instance per-request\nexport default {\n  fetch(request, env, ctx) {\n    const db = drizzle(env.DB, { schema })\n    const auth = betterAuth({ database: drizzleAdapter(db, { provider: \"sqlite\" }) })\n    return auth.handler(request)\n  }\n}\n```\n\n**Community Validation**: Multiple production implementations confirm this pattern (Medium, AnswerOverflow, official Hono examples).\n\n---\n\n## Framework Integrations\n\n### TanStack Start\n\n**⚠️ CRITICAL**: TanStack Start requires the `reactStartCookies` plugin to handle cookie setting properly.\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { drizzleAdapter } from \"better-auth\u002Fadapters\u002Fdrizzle\";\nimport { reactStartCookies } from \"better-auth\u002Freact-start\";\n\nexport const auth = betterAuth({\n  database: drizzleAdapter(db, { provider: \"sqlite\" }),\n  plugins: [\n    twoFactor(),\n    organization(),\n    reactStartCookies(), \u002F\u002F ⚠️ MUST be LAST plugin\n  ],\n});\n```\n\n**Why it's needed**: TanStack Start uses a special cookie handling system. Without this plugin, auth functions like `signInEmail()` and `signUpEmail()` won't set cookies properly, causing authentication to fail.\n\n**Important**: The `reactStartCookies` plugin **must be the last plugin in the array**.\n\n**Session Nullability Pattern**: When using `useSession()` in TanStack Start, the session object always exists, but `session.user` and `session.session` are `null` when not logged in:\n\n```typescript\nconst { data: session } = authClient.useSession()\n\n\u002F\u002F When NOT logged in:\nconsole.log(session) \u002F\u002F { user: null, session: null }\nconsole.log(!!session) \u002F\u002F true (unexpected!)\n\n\u002F\u002F Correct check:\nif (session?.user) {\n  \u002F\u002F User is logged in\n}\n```\n\n**Always check `session?.user` or `session?.session`, not just `session`**. This is expected behavior (session object container always exists).\n\n**API Route Setup** (`\u002Fsrc\u002Froutes\u002Fapi\u002Fauth\u002F$.ts`):\n```typescript\nimport { auth } from '@\u002Flib\u002Fauth'\nimport { createFileRoute } from '@tanstack\u002Freact-router'\n\nexport const Route = createFileRoute('\u002Fapi\u002Fauth\u002F$')({\n  server: {\n    handlers: {\n      GET: ({ request }) => auth.handler(request),\n      POST: ({ request }) => auth.handler(request),\n    },\n  },\n})\n```\n\n? **Official Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Ftanstack\n\n---\n\n## Available Plugins (v1.4+)\n\nBetter Auth provides plugins for advanced authentication features:\n\n| Plugin | Import | Description | Docs |\n|--------|--------|-------------|------|\n| **OAuth 2.1 Provider** | `better-auth\u002Fplugins` | Build OAuth 2.1 provider with PKCE, JWT tokens, consent flows (replaces MCP & OIDC plugins) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Foauth-provider) |\n| **SSO** | `better-auth\u002Fplugins` | Enterprise Single Sign-On with OIDC, OAuth2, and SAML 2.0 support | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fsso) |\n| **Stripe** | `better-auth\u002Fplugins` | Payment and subscription management with flexible lifecycle handling | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fstripe) |\n| **MCP** | `better-auth\u002Fplugins` | ⚠️ **Deprecated** - Use OAuth 2.1 Provider instead | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmcp) |\n| **Expo** | `better-auth\u002Fexpo` | React Native\u002FExpo with `webBrowserOptions` and last-login-method tracking | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Fexpo) |\n\n### OAuth 2.1 Provider Plugin (New in v1.4.9)\n\nBuild your own OAuth provider for MCP servers, third-party apps, or API access:\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { oauthProvider } from \"better-auth\u002Fplugins\";\nimport { jwt } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  plugins: [\n    jwt(), \u002F\u002F Required for token signing\n    oauthProvider({\n      \u002F\u002F Token expiration (seconds)\n      accessTokenExpiresIn: 3600,      \u002F\u002F 1 hour\n      refreshTokenExpiresIn: 2592000,  \u002F\u002F 30 days\n      authorizationCodeExpiresIn: 600, \u002F\u002F 10 minutes\n    }),\n  ],\n});\n```\n\n**Key Features:**\n- **OAuth 2.1 compliant** - PKCE mandatory, S256 only, no implicit flow\n- **Three grant types**: `authorization_code`, `refresh_token`, `client_credentials`\n- **JWT or opaque tokens** - Configurable token format\n- **Dynamic client registration** - RFC 7591 compliant\n- **Consent management** - Skip consent for trusted clients\n- **OIDC UserInfo endpoint** - `\u002Foauth2\u002Fuserinfo` with scope-based claims\n\n**Required Well-Known Endpoints:**\n\n```typescript\n\u002F\u002F app\u002Fapi\u002F.well-known\u002Foauth-authorization-server\u002Froute.ts\nexport async function GET() {\n  return Response.json({\n    issuer: process.env.BETTER_AUTH_URL,\n    authorization_endpoint: `${process.env.BETTER_AUTH_URL}\u002Fapi\u002Fauth\u002Foauth2\u002Fauthorize`,\n    token_endpoint: `${process.env.BETTER_AUTH_URL}\u002Fapi\u002Fauth\u002Foauth2\u002Ftoken`,\n    \u002F\u002F ... other metadata\n  });\n}\n```\n\n**Create OAuth Client:**\n\n```typescript\nconst client = await auth.api.createOAuthClient({\n  body: {\n    name: \"My MCP Server\",\n    redirectURLs: [\"https:\u002F\u002Fclaude.ai\u002Fcallback\"],\n    type: \"public\", \u002F\u002F or \"confidential\"\n  },\n});\n\u002F\u002F Returns: { clientId, clientSecret (if confidential) }\n```\n\n? **Full Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Foauth-provider\n\n⚠️ **Note**: This plugin is in active development and may not be suitable for production use yet.\n\n---\n\n### Additional Plugins Reference\n\n| Plugin | Description | Docs |\n|--------|-------------|------|\n| **Bearer** | API token auth (alternative to cookies for APIs) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fbearer) |\n| **One Tap** | Google One Tap frictionless sign-in | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fone-tap) |\n| **SCIM** | Enterprise user provisioning (SCIM 2.0) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fscim) |\n| **Anonymous** | Guest user access without PII | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fanonymous) |\n| **Username** | Username-based sign-in (alternative to email) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fusername) |\n| **Generic OAuth** | Custom OAuth providers with PKCE | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fgeneric-oauth) |\n| **Multi-Session** | Multiple accounts in same browser | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmulti-session) |\n| **API Key** | Token-based auth with rate limits | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fapi-key) |\n\n#### Bearer Token Plugin\n\nFor API-only authentication (mobile apps, CLI tools, third-party integrations):\n\n```typescript\nimport { bearer } from \"better-auth\u002Fplugins\";\nimport { bearerClient } from \"better-auth\u002Fclient\u002Fplugins\";\n\n\u002F\u002F Server\nexport const auth = betterAuth({\n  plugins: [bearer()],\n});\n\n\u002F\u002F Client - Store token after sign-in\nconst { token } = await authClient.signIn.email({ email, password });\nlocalStorage.setItem(\"auth_token\", token);\n\n\u002F\u002F Client - Configure fetch to include token\nconst authClient = createAuthClient({\n  plugins: [bearerClient()],\n  fetchOptions: {\n    auth: { type: \"Bearer\", token: () => localStorage.getItem(\"auth_token\") },\n  },\n});\n```\n\n#### Google One Tap Plugin\n\nFrictionless single-tap sign-in for users already signed into Google:\n\n```typescript\nimport { oneTap } from \"better-auth\u002Fplugins\";\nimport { oneTapClient } from \"better-auth\u002Fclient\u002Fplugins\";\n\n\u002F\u002F Server\nexport const auth = betterAuth({\n  plugins: [oneTap()],\n});\n\n\u002F\u002F Client\nauthClient.oneTap({\n  onSuccess: (session) => {\n    window.location.href = \"\u002Fdashboard\";\n  },\n});\n```\n\n**Requirement**: Configure authorized JavaScript origins in Google Cloud Console.\n\n#### Anonymous Plugin\n\nGuest access without requiring email\u002Fpassword:\n\n```typescript\nimport { anonymous } from \"better-auth\u002Fplugins\";\n\n\u002F\u002F Server\nexport const auth = betterAuth({\n  plugins: [\n    anonymous({\n      emailDomainName: \"anon.example.com\", \u002F\u002F temp@{id}.anon.example.com\n      onLinkAccount: async ({ anonymousUser, newUser }) => {\n        \u002F\u002F Migrate anonymous user data to linked account\n        await migrateUserData(anonymousUser.id, newUser.id);\n      },\n    }),\n  ],\n});\n\n\u002F\u002F Client\nawait authClient.signIn.anonymous();\n\u002F\u002F Later: user can link to real account via signIn.social\u002Femail\n```\n\n#### Generic OAuth Plugin\n\nAdd custom OAuth providers not in the built-in list:\n\n```typescript\nimport { genericOAuth } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  plugins: [\n    genericOAuth({\n      config: [\n        {\n          providerId: \"linear\",\n          clientId: env.LINEAR_CLIENT_ID,\n          clientSecret: env.LINEAR_CLIENT_SECRET,\n          discoveryUrl: \"https:\u002F\u002Flinear.app\u002F.well-known\u002Fopenid-configuration\",\n          scopes: [\"openid\", \"email\", \"profile\"],\n          pkce: true, \u002F\u002F Recommended\n        },\n      ],\n    }),\n  ],\n});\n```\n\n**Callback URL pattern**: `{baseURL}\u002Fapi\u002Fauth\u002Foauth2\u002Fcallback\u002F{providerId}`\n\n---\n\n## Rate Limiting\n\nBuilt-in rate limiting with customizable rules:\n\n```typescript\nexport const auth = betterAuth({\n  rateLimit: {\n    window: 60,  \u002F\u002F seconds (default: 60)\n    max: 100,    \u002F\u002F requests per window (default: 100)\n\n    \u002F\u002F Custom rules for sensitive endpoints\n    customRules: {\n      \"\u002Fsign-in\u002Femail\": { window: 10, max: 3 },\n      \"\u002Ftwo-factor\u002F*\": { window: 10, max: 3 },\n      \"\u002Fforget-password\": { window: 60, max: 5 },\n    },\n\n    \u002F\u002F Use Redis\u002FKV for distributed systems\n    storage: \"secondary-storage\", \u002F\u002F or \"database\"\n  },\n\n  \u002F\u002F Secondary storage for rate limiting\n  secondaryStorage: {\n    get: async (key) => env.KV.get(key),\n    set: async (key, value, ttl) => env.KV.put(key, value, { expirationTtl: ttl }),\n    delete: async (key) => env.KV.delete(key),\n  },\n});\n```\n\n**Note**: Server-side calls via `auth.api.*` bypass rate limiting.\n\n---\n\n## Stateless Sessions (v1.4.0+)\n\nStore sessions entirely in signed cookies without database storage:\n\n```typescript\nexport const auth = betterAuth({\n  session: {\n    \u002F\u002F Stateless: No database storage, session lives in cookie only\n    storage: undefined, \u002F\u002F or omit entirely\n\n    \u002F\u002F Cookie configuration\n    cookieCache: {\n      enabled: true,\n      maxAge: 60 * 60 * 24 * 7, \u002F\u002F 7 days\n      encoding: \"jwt\", \u002F\u002F Use JWT for stateless (not \"compact\")\n    },\n\n    \u002F\u002F Session expiration\n    expiresIn: 60 * 60 * 24 * 7, \u002F\u002F 7 days\n  },\n});\n```\n\n**When to Use:**\n\n| Storage Type | Use Case | Tradeoffs |\n|--------------|----------|-----------|\n| **Stateless (cookie-only)** | Read-heavy apps, edge\u002Fserverless, no revocation needed | Can't revoke sessions, limited payload size |\n| **D1 Database** | Full session management, audit trails, revocation | Eventual consistency issues |\n| **KV Storage** | Strong consistency, high read performance | Extra binding setup |\n\n**Key Points:**\n- Stateless sessions can't be revoked (user must wait for expiry)\n- Cookie size limit ~4KB (limits session data)\n- Use `encoding: \"jwt\"` for interoperability, `\"jwe\"` for encrypted\n- Server must have consistent `BETTER_AUTH_SECRET` across all instances\n\n---\n\n## JWT Key Rotation (v1.4.0+)\n\nAutomatically rotate JWT signing keys for enhanced security:\n\n```typescript\nimport { jwt } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  plugins: [\n    jwt({\n      \u002F\u002F Key rotation (optional, enterprise security)\n      keyRotation: {\n        enabled: true,\n        rotationInterval: 60 * 60 * 24 * 30, \u002F\u002F Rotate every 30 days\n        keepPreviousKeys: 3, \u002F\u002F Keep 3 old keys for validation\n      },\n\n      \u002F\u002F Custom signing algorithm (default: HS256)\n      algorithm: \"RS256\", \u002F\u002F Requires asymmetric keys\n\n      \u002F\u002F JWKS endpoint (auto-generated at \u002Fapi\u002Fauth\u002Fjwks)\n      exposeJWKS: true,\n    }),\n  ],\n});\n```\n\n**Key Points:**\n- Key rotation prevents compromised key from having indefinite validity\n- Old keys are kept temporarily to validate existing tokens\n- JWKS endpoint at `\u002Fapi\u002Fauth\u002Fjwks` for external services\n- Use RS256 for public key verification (microservices)\n- HS256 (default) for single-service apps\n\n---\n\n## Provider Scopes Reference\n\nCommon OAuth providers and the scopes needed for user data:\n\n| Provider | Scope | Returns |\n|----------|-------|---------|\n| **Google** | `openid` | User ID only |\n| | `email` | Email address, email_verified |\n| | `profile` | Name, avatar (picture), locale |\n| **GitHub** | `user:email` | Email address (may be private) |\n| | `read:user` | Name, avatar, profile URL, bio |\n| **Microsoft** | `openid` | User ID only |\n| | `email` | Email address |\n| | `profile` | Name, locale |\n| | `User.Read` | Full profile from Graph API |\n| **Discord** | `identify` | Username, avatar, discriminator |\n| | `email` | Email address |\n| **Apple** | `name` | First\u002Flast name (first auth only) |\n| | `email` | Email or relay address |\n| **Patreon** | `identity` | User ID, name |\n| | `identity[email]` | Email address |\n| **Vercel** | (auto) | Email, name, avatar |\n\n**Configuration Example:**\n\n```typescript\nsocialProviders: {\n  google: {\n    clientId: env.GOOGLE_CLIENT_ID,\n    clientSecret: env.GOOGLE_CLIENT_SECRET,\n    scope: [\"openid\", \"email\", \"profile\"], \u002F\u002F All user data\n  },\n  github: {\n    clientId: env.GITHUB_CLIENT_ID,\n    clientSecret: env.GITHUB_CLIENT_SECRET,\n    scope: [\"user:email\", \"read:user\"], \u002F\u002F Email + full profile\n  },\n  microsoft: {\n    clientId: env.MS_CLIENT_ID,\n    clientSecret: env.MS_CLIENT_SECRET,\n    scope: [\"openid\", \"email\", \"profile\", \"User.Read\"],\n  },\n}\n```\n\n---\n\n## Session Cookie Caching\n\nThree encoding strategies for session cookies:\n\n| Strategy | Format | Use Case |\n|----------|--------|----------|\n| **Compact** (default) | Base64url + HMAC-SHA256 | Smallest, fastest |\n| **JWT** | Standard JWT | Interoperable |\n| **JWE** | A256CBC-HS512 encrypted | Most secure |\n\n```typescript\nexport const auth = betterAuth({\n  session: {\n    cookieCache: {\n      enabled: true,\n      maxAge: 300, \u002F\u002F 5 minutes\n      encoding: \"compact\", \u002F\u002F or \"jwt\" or \"jwe\"\n    },\n    freshAge: 60 * 60 * 24, \u002F\u002F 1 day - operations requiring fresh session\n  },\n});\n```\n\n**Fresh sessions**: Some sensitive operations require recently created sessions. Configure `freshAge` to control this window.\n\n---\n\n## New Social Providers (v1.4.9+)\n\n```typescript\nsocialProviders: {\n  \u002F\u002F Patreon - Creator economy\n  patreon: {\n    clientId: env.PATREON_CLIENT_ID,\n    clientSecret: env.PATREON_CLIENT_SECRET,\n    scope: [\"identity\", \"identity[email]\"],\n  },\n\n  \u002F\u002F Kick - Streaming platform (with refresh tokens)\n  kick: {\n    clientId: env.KICK_CLIENT_ID,\n    clientSecret: env.KICK_CLIENT_SECRET,\n  },\n\n  \u002F\u002F Vercel - Developer platform\n  vercel: {\n    clientId: env.VERCEL_CLIENT_ID,\n    clientSecret: env.VERCEL_CLIENT_SECRET,\n  },\n}\n```\n\n---\n\n## Cloudflare Workers Requirements\n\n**⚠️ CRITICAL**: Cloudflare Workers require AsyncLocalStorage support:\n\n```toml\n# wrangler.toml\ncompatibility_flags = [\"nodejs_compat\"]\n# or for older Workers:\n# compatibility_flags = [\"nodejs_als\"]\n```\n\nWithout this flag, better-auth will fail with context-related errors.\n\n---\n\n## Database Hooks\n\nExecute custom logic during database operations:\n\n```typescript\nexport const auth = betterAuth({\n  databaseHooks: {\n    user: {\n      create: {\n        before: async (user, ctx) => {\n          \u002F\u002F Validate or modify before creation\n          if (user.email?.endsWith(\"@blocked.com\")) {\n            throw new APIError(\"BAD_REQUEST\", { message: \"Email domain not allowed\" });\n          }\n          return { data: { ...user, role: \"member\" } };\n        },\n        after: async (user, ctx) => {\n          \u002F\u002F Send welcome email, create related records, etc.\n          await sendWelcomeEmail(user.email);\n          await createDefaultWorkspace(user.id);\n        },\n      },\n    },\n    session: {\n      create: {\n        after: async (session, ctx) => {\n          \u002F\u002F Audit logging\n          await auditLog.create({ action: \"session_created\", userId: session.userId });\n        },\n      },\n    },\n  },\n});\n```\n\n**Available hooks**: `create`, `update` for `user`, `session`, `account`, `verification` tables.\n\n---\n\n## Expo\u002FReact Native Integration\n\nComplete mobile integration pattern:\n\n```typescript\n\u002F\u002F Client setup with secure storage\nimport { expoClient } from \"@better-auth\u002Fexpo\";\nimport * as SecureStore from \"expo-secure-store\";\n\nconst authClient = createAuthClient({\n  baseURL: \"https:\u002F\u002Fapi.example.com\",\n  plugins: [expoClient({ storage: SecureStore })],\n});\n\n\u002F\u002F OAuth with deep linking\nawait authClient.signIn.social({\n  provider: \"google\",\n  callbackURL: \"myapp:\u002F\u002Fauth\u002Fcallback\", \u002F\u002F Deep link\n});\n\n\u002F\u002F Or use ID token verification (no redirect)\nawait authClient.signIn.social({\n  provider: \"google\",\n  idToken: {\n    token: googleIdToken,\n    nonce: generatedNonce,\n  },\n});\n\n\u002F\u002F Authenticated requests\nconst cookie = await authClient.getCookie();\nawait fetch(\"https:\u002F\u002Fapi.example.com\u002Fdata\", {\n  headers: { Cookie: cookie },\n  credentials: \"omit\",\n});\n```\n\n**app.json deep link setup**:\n```json\n{\n  \"expo\": {\n    \"scheme\": \"myapp\"\n  }\n}\n```\n\n**Server trustedOrigins** (development):\n```typescript\ntrustedOrigins: [\"exp:\u002F\u002F**\", \"myapp:\u002F\u002F\"]\n```\n\n---\n\n## API Reference\n\n### Overview: What You Get For Free\n\nWhen you call `auth.handler()`, better-auth automatically exposes **80+ production-ready REST endpoints** at `\u002Fapi\u002Fauth\u002F*`. Every endpoint is also available as a **server-side method** via `auth.api.*` for programmatic use.\n\nThis dual-layer API system means:\n- **Clients** (React, Vue, mobile apps) call HTTP endpoints directly\n- **Server-side code** (middleware, background jobs) uses `auth.api.*` methods\n- **Zero boilerplate** - no need to write auth endpoints manually\n\n**Time savings**: Building this from scratch = ~220 hours. With better-auth = ~4-8 hours. **97% reduction.**\n\n---\n\n### Auto-Generated HTTP Endpoints\n\nAll endpoints are automatically exposed at `\u002Fapi\u002Fauth\u002F*` when using `auth.handler()`.\n\n#### Core Authentication Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fsign-up\u002Femail` | POST | Register with email\u002Fpassword |\n| `\u002Fsign-in\u002Femail` | POST | Authenticate with email\u002Fpassword |\n| `\u002Fsign-out` | POST | Logout user |\n| `\u002Fchange-password` | POST | Update password (requires current password) |\n| `\u002Fforget-password` | POST | Initiate password reset flow |\n| `\u002Freset-password` | POST | Complete password reset with token |\n| `\u002Fsend-verification-email` | POST | Send email verification link |\n| `\u002Fverify-email` | GET | Verify email with token (`?token=\u003Ctoken>`) |\n| `\u002Fget-session` | GET | Retrieve current session |\n| `\u002Flist-sessions` | GET | Get all active user sessions |\n| `\u002Frevoke-session` | POST | End specific session |\n| `\u002Frevoke-other-sessions` | POST | End all sessions except current |\n| `\u002Frevoke-sessions` | POST | End all user sessions |\n| `\u002Fupdate-user` | POST | Modify user profile (name, image) |\n| `\u002Fchange-email` | POST | Update email address |\n| `\u002Fset-password` | POST | Add password to OAuth-only account |\n| `\u002Fdelete-user` | POST | Remove user account |\n| `\u002Flist-accounts` | GET | Get linked authentication providers |\n| `\u002Flink-social` | POST | Connect OAuth provider to account |\n| `\u002Funlink-account` | POST | Disconnect provider |\n\n#### Social OAuth Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fsign-in\u002Fsocial` | POST | Initiate OAuth flow (provider specified in body) |\n| `\u002Fcallback\u002F:provider` | GET | OAuth callback handler (e.g., `\u002Fcallback\u002Fgoogle`) |\n| `\u002Fget-access-token` | GET | Retrieve provider access token |\n\n**Example OAuth flow**:\n```typescript\n\u002F\u002F Client initiates\nawait authClient.signIn.social({\n  provider: \"google\",\n  callbackURL: \"\u002Fdashboard\",\n});\n\n\u002F\u002F better-auth handles redirect to Google\n\u002F\u002F Google redirects back to \u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle\n\u002F\u002F better-auth creates session automatically\n```\n\n---\n\n#### Plugin Endpoints\n\n##### Two-Factor Authentication (2FA Plugin)\n\n```typescript\nimport { twoFactor } from \"better-auth\u002Fplugins\";\n```\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Ftwo-factor\u002Fenable` | POST | Activate 2FA for user |\n| `\u002Ftwo-factor\u002Fdisable` | POST | Deactivate 2FA |\n| `\u002Ftwo-factor\u002Fget-totp-uri` | GET | Get QR code URI for authenticator app |\n| `\u002Ftwo-factor\u002Fverify-totp` | POST | Validate TOTP code from authenticator |\n| `\u002Ftwo-factor\u002Fsend-otp` | POST | Send OTP via email |\n| `\u002Ftwo-factor\u002Fverify-otp` | POST | Validate email OTP |\n| `\u002Ftwo-factor\u002Fgenerate-backup-codes` | POST | Create recovery codes |\n| `\u002Ftwo-factor\u002Fverify-backup-code` | POST | Use backup code for login |\n| `\u002Ftwo-factor\u002Fview-backup-codes` | GET | View current backup codes |\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002F2fa\n\n##### Organization Plugin (Multi-Tenant SaaS)\n\n```typescript\nimport { organization } from \"better-auth\u002Fplugins\";\n```\n\n**Organizations** (10 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Fcreate` | POST | Create organization |\n| `\u002Forganization\u002Flist` | GET | List user's organizations |\n| `\u002Forganization\u002Fget-full` | GET | Get complete org details |\n| `\u002Forganization\u002Fupdate` | PUT | Modify organization |\n| `\u002Forganization\u002Fdelete` | DELETE | Remove organization |\n| `\u002Forganization\u002Fcheck-slug` | GET | Verify slug availability |\n| `\u002Forganization\u002Fset-active` | POST | Set active organization context |\n\n**Members** (8 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Flist-members` | GET | Get organization members |\n| `\u002Forganization\u002Fadd-member` | POST | Add member directly |\n| `\u002Forganization\u002Fremove-member` | DELETE | Remove member |\n| `\u002Forganization\u002Fupdate-member-role` | PUT | Change member role |\n| `\u002Forganization\u002Fget-active-member` | GET | Get current member info |\n| `\u002Forganization\u002Fleave` | POST | Leave organization |\n\n**Invitations** (7 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Finvite-member` | POST | Send invitation email |\n| `\u002Forganization\u002Faccept-invitation` | POST | Accept invite |\n| `\u002Forganization\u002Freject-invitation` | POST | Reject invite |\n| `\u002Forganization\u002Fcancel-invitation` | POST | Cancel pending invite |\n| `\u002Forganization\u002Fget-invitation` | GET | Get invitation details |\n| `\u002Forganization\u002Flist-invitations` | GET | List org invitations |\n| `\u002Forganization\u002Flist-user-invitations` | GET | List user's pending invites |\n\n**Teams** (8 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Fcreate-team` | POST | Create team within org |\n| `\u002Forganization\u002Flist-teams` | GET | List organization teams |\n| `\u002Forganization\u002Fupdate-team` | PUT | Modify team |\n| `\u002Forganization\u002Fremove-team` | DELETE | Remove team |\n| `\u002Forganization\u002Fset-active-team` | POST | Set active team context |\n| `\u002Forganization\u002Flist-team-members` | GET | List team members |\n| `\u002Forganization\u002Fadd-team-member` | POST | Add member to team |\n| `\u002Forganization\u002Fremove-team-member` | DELETE | Remove team member |\n\n**Permissions & Roles** (6 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Fhas-permission` | POST | Check if user has permission |\n| `\u002Forganization\u002Fcreate-role` | POST | Create custom role |\n| `\u002Forganization\u002Fdelete-role` | DELETE | Delete custom role |\n| `\u002Forganization\u002Flist-roles` | GET | List all roles |\n| `\u002Forganization\u002Fget-role` | GET | Get role details |\n| `\u002Forganization\u002Fupdate-role` | PUT | Modify role permissions |\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Forganization\n\n##### Admin Plugin\n\n```typescript\nimport { admin } from \"better-auth\u002Fplugins\";\n\n\u002F\u002F v1.4.10 configuration options\nadmin({\n  defaultRole: \"user\",\n  adminRoles: [\"admin\"],\n  adminUserIds: [\"user_abc123\"], \u002F\u002F Always grant admin to specific users\n  impersonationSessionDuration: 3600, \u002F\u002F 1 hour (seconds)\n  allowImpersonatingAdmins: false, \u002F\u002F ⚠️ Default changed in v1.4.6\n  defaultBanReason: \"Violation of Terms of Service\",\n  bannedUserMessage: \"Your account has been suspended\",\n})\n```\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fadmin\u002Fcreate-user` | POST | Create user as admin |\n| `\u002Fadmin\u002Flist-users` | GET | List all users (with filters\u002Fpagination) |\n| `\u002Fadmin\u002Fset-role` | POST | Assign user role |\n| `\u002Fadmin\u002Fset-user-password` | POST | Change user password |\n| `\u002Fadmin\u002Fupdate-user` | PUT | Modify user details |\n| `\u002Fadmin\u002Fremove-user` | DELETE | Delete user account |\n| `\u002Fadmin\u002Fban-user` | POST | Ban user account (with optional expiry) |\n| `\u002Fadmin\u002Funban-user` | POST | Unban user |\n| `\u002Fadmin\u002Flist-user-sessions` | GET | Get user's active sessions |\n| `\u002Fadmin\u002Frevoke-user-session` | DELETE | End specific user session |\n| `\u002Fadmin\u002Frevoke-user-sessions` | DELETE | End all user sessions |\n| `\u002Fadmin\u002Fimpersonate-user` | POST | Start impersonating user |\n| `\u002Fadmin\u002Fstop-impersonating` | POST | End impersonation session |\n\n**⚠️ Breaking Change (v1.4.6)**: `allowImpersonatingAdmins` now defaults to `false`. Set to `true` explicitly if you need admin-on-admin impersonation.\n\n**Custom Roles with Permissions (v1.4.10):**\n\n```typescript\nimport { createAccessControl } from \"better-auth\u002Fplugins\u002Faccess\";\n\n\u002F\u002F Define resources and permissions\nconst ac = createAccessControl({\n  user: [\"create\", \"read\", \"update\", \"delete\", \"ban\", \"impersonate\"],\n  project: [\"create\", \"read\", \"update\", \"delete\", \"share\"],\n} as const);\n\n\u002F\u002F Create custom roles\nconst supportRole = ac.newRole({\n  user: [\"read\", \"ban\"],      \u002F\u002F Can view and ban users\n  project: [\"read\"],          \u002F\u002F Can view projects\n});\n\nconst managerRole = ac.newRole({\n  user: [\"read\", \"update\"],\n  project: [\"create\", \"read\", \"update\", \"delete\"],\n});\n\n\u002F\u002F Use in plugin\nadmin({\n  ac,\n  roles: {\n    support: supportRole,\n    manager: managerRole,\n  },\n})\n```\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fadmin\n\n##### Other Plugin Endpoints\n\n**Passkey Plugin** (5 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fpasskey):\n- `\u002Fpasskey\u002Fadd`, `\u002Fsign-in\u002Fpasskey`, `\u002Fpasskey\u002Flist`, `\u002Fpasskey\u002Fdelete`, `\u002Fpasskey\u002Fupdate`\n\n**Magic Link Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmagic-link):\n- `\u002Fsign-in\u002Fmagic-link`, `\u002Fmagic-link\u002Fverify`\n\n**Username Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fusername):\n- `\u002Fsign-in\u002Fusername`, `\u002Fusername\u002Fis-available`\n\n**Phone Number Plugin** (5 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fphone-number):\n- `\u002Fsign-in\u002Fphone-number`, `\u002Fphone-number\u002Fsend-otp`, `\u002Fphone-number\u002Fverify`, `\u002Fphone-number\u002Frequest-password-reset`, `\u002Fphone-number\u002Freset-password`\n\n**Email OTP Plugin** (6 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Femail-otp):\n- `\u002Femail-otp\u002Fsend-verification-otp`, `\u002Femail-otp\u002Fcheck-verification-otp`, `\u002Fsign-in\u002Femail-otp`, `\u002Femail-otp\u002Fverify-email`, `\u002Fforget-password\u002Femail-otp`, `\u002Femail-otp\u002Freset-password`\n\n**Anonymous Plugin** (1 endpoint) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fanonymous):\n- `\u002Fsign-in\u002Fanonymous`\n\n**JWT Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fjwt):\n- `\u002Ftoken` (get JWT), `\u002Fjwks` (public key for verification)\n\n**OpenAPI Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fopen-api):\n- `\u002Freference` (interactive API docs with Scalar UI)\n- `\u002Fgenerate-openapi-schema` (get OpenAPI spec as JSON)\n\n---\n\n### Server-Side API Methods (`auth.api.*`)\n\nEvery HTTP endpoint has a corresponding server-side method. Use these for:\n- **Server-side middleware** (protecting routes)\n- **Background jobs** (user cleanup, notifications)\n- **Admin operations** (bulk user management)\n- **Custom auth flows** (programmatic session creation)\n\n#### Core API Methods\n\n```typescript\n\u002F\u002F Authentication\nawait auth.api.signUpEmail({\n  body: { email, password, name },\n  headers: request.headers,\n});\n\nawait auth.api.signInEmail({\n  body: { email, password, rememberMe: true },\n  headers: request.headers,\n});\n\nawait auth.api.signOut({ headers: request.headers });\n\n\u002F\u002F Session Management\nconst session = await auth.api.getSession({ headers: request.headers });\n\nawait auth.api.listSessions({ headers: request.headers });\n\nawait auth.api.revokeSession({\n  body: { token: \"session_token_here\" },\n  headers: request.headers,\n});\n\n\u002F\u002F User Management\nawait auth.api.updateUser({\n  body: { name: \"New Name\", image: \"https:\u002F\u002F...\" },\n  headers: request.headers,\n});\n\nawait auth.api.changeEmail({\n  body: { newEmail: \"newemail@example.com\" },\n  headers: request.headers,\n});\n\nawait auth.api.deleteUser({\n  body: { password: \"current_password\" },\n  headers: request.headers,\n});\n\n\u002F\u002F Account Linking\nawait auth.api.linkSocialAccount({\n  body: { provider: \"google\" },\n  headers: request.headers,\n});\n\nawait auth.api.unlinkAccount({\n  body: { providerId: \"google\", accountId: \"google_123\" },\n  headers: request.headers,\n});\n```\n\n#### Plugin API Methods\n\n**2FA Plugin**:\n```typescript\n\u002F\u002F Enable 2FA\nconst { totpUri, backupCodes } = await auth.api.enableTwoFactor({\n  body: { issuer: \"MyApp\" },\n  headers: request.headers,\n});\n\n\u002F\u002F Verify TOTP code\nawait auth.api.verifyTOTP({\n  body: { code: \"123456\", trustDevice: true },\n  headers: request.headers,\n});\n\n\u002F\u002F Generate backup codes\nconst { backupCodes } = await auth.api.generateBackupCodes({\n  headers: request.headers,\n});\n```\n\n**Organization Plugin**:\n```typescript\n\u002F\u002F Create organization\nconst org = await auth.api.createOrganization({\n  body: { name: \"Acme Corp\", slug: \"acme\" },\n  headers: request.headers,\n});\n\n\u002F\u002F Add member\nawait auth.api.addMember({\n  body: {\n    userId: \"user_123\",\n    role: \"admin\",\n    organizationId: org.id,\n  },\n  headers: request.headers,\n});\n\n\u002F\u002F Check permissions\nconst hasPermission = await auth.api.hasPermission({\n  body: {\n    organizationId: org.id,\n    permission: \"users:delete\",\n  },\n  headers: request.headers,\n});\n```\n\n**Admin Plugin**:\n```typescript\n\u002F\u002F List users with pagination\nconst users = await auth.api.listUsers({\n  query: {\n    search: \"john\",\n    limit: 10,\n    offset: 0,\n    sortBy: \"createdAt\",\n    sortOrder: \"desc\",\n  },\n  headers: request.headers,\n});\n\n\u002F\u002F Ban user\nawait auth.api.banUser({\n  body: {\n    userId: \"user_123\",\n    reason: \"Violation of ToS\",\n    expiresAt: new Date(\"2025-12-31\"),\n  },\n  headers: request.headers,\n});\n\n\u002F\u002F Impersonate user (for admin support)\nconst impersonationSession = await auth.api.impersonateUser({\n  body: {\n    userId: \"user_123\",\n    expiresIn: 3600, \u002F\u002F 1 hour\n  },\n  headers: request.headers,\n});\n```\n\n---\n\n### When to Use Which\n\n| Use Case | Use HTTP Endpoints | Use `auth.api.*` Methods |\n|----------|-------------------|--------------------------|\n| **Client-side auth** | ✅ Yes | ❌ No |\n| **Server middleware** | ❌ No | ✅ Yes |\n| **Background jobs** | ❌ No | ✅ Yes |\n| **Admin dashboards** | ✅ Yes (from client) | ✅ Yes (from server) |\n| **Custom auth flows** | ❌ No | ✅ Yes |\n| **Mobile apps** | ✅ Yes | ❌ No |\n| **API routes** | ✅ Yes (proxy to handler) | ✅ Yes (direct calls) |\n\n**Example: Protected Route Middleware**\n\n```typescript\nimport { Hono } from \"hono\";\nimport { createAuth } from \".\u002Fauth\";\nimport { createDatabase } from \".\u002Fdb\";\n\nconst app = new Hono\u003C{ Bindings: Env }>();\n\n\u002F\u002F Middleware using server-side API\napp.use(\"\u002Fapi\u002Fprotected\u002F*\", async (c, next) => {\n  const db = createDatabase(c.env.DB);\n  const auth = createAuth(db, c.env);\n\n  \u002F\u002F Use server-side method\n  const session = await auth.api.getSession({\n    headers: c.req.raw.headers,\n  });\n\n  if (!session) {\n    return c.json({ error: \"Unauthorized\" }, 401);\n  }\n\n  \u002F\u002F Attach to context\n  c.set(\"user\", session.user);\n  c.set(\"session\", session.session);\n\n  await next();\n});\n\n\u002F\u002F Protected route\napp.get(\"\u002Fapi\u002Fprotected\u002Fprofile\", async (c) => {\n  const user = c.get(\"user\");\n  return c.json({ user });\n});\n```\n\n---\n\n### Discovering Available Endpoints\n\nUse the **OpenAPI plugin** to see all endpoints in your configuration:\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { openAPI } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  database: \u002F* ... *\u002F,\n  plugins: [\n    openAPI(), \u002F\u002F Adds \u002Fapi\u002Fauth\u002Freference endpoint\n  ],\n});\n```\n\n**Interactive documentation**: Visit `http:\u002F\u002Flocalhost:8787\u002Fapi\u002Fauth\u002Freference`\n\nThis shows a **Scalar UI** with:\n- ✅ All available endpoints grouped by feature\n- ✅ Request\u002Fresponse schemas with types\n- ✅ Try-it-out functionality (test endpoints in browser)\n- ✅ Authentication requirements\n- ✅ Code examples in multiple languages\n\n**Programmatic access**:\n```typescript\nconst schema = await auth.api.generateOpenAPISchema();\nconsole.log(JSON.stringify(schema, null, 2));\n\u002F\u002F Returns full OpenAPI 3.0 spec\n```\n\n---\n\n### Quantified Time Savings\n\n**Building from scratch** (manual implementation):\n- Core auth endpoints (sign-up, sign-in, OAuth, sessions): **40 hours**\n- Email verification & password reset: **10 hours**\n- 2FA system (TOTP, backup codes, email OTP): **20 hours**\n- Organizations (teams, invitations, RBAC): **60 hours**\n- Admin panel (user management, impersonation): **30 hours**\n- Testing & debugging: **50 hours**\n- Security hardening: **20 hours**\n\n**Total manual effort**: **~220 hours** (5.5 weeks full-time)\n\n**With better-auth**:\n- Initial setup: **2-4 hours**\n- Customization & styling: **2-4 hours**\n\n**Total with better-auth**: **4-8 hours**\n\n**Savings**: **~97% development time**\n\n---\n\n### Key Takeaway\n\nbetter-auth provides **80+ production-ready endpoints** covering:\n- ✅ Core authentication (20 endpoints)\n- ✅ 2FA & passwordless (15 endpoints)\n- ✅ Organizations & teams (35 endpoints)\n- ✅ Admin & user management (15 endpoints)\n- ✅ Social OAuth (auto-configured callbacks)\n- ✅ OpenAPI documentation (interactive UI)\n\n**You write zero endpoint code.** Just configure features and call `auth.handler()`.\n\n---\n\n## Known Issues & Solutions\n\n### Issue 1: \"d1Adapter is not exported\" Error\n\n**Problem**: Code shows `import { d1Adapter } from 'better-auth\u002Fadapters\u002Fd1'` but this doesn't exist.\n\n**Symptoms**: TypeScript error or runtime error about missing export.\n\n**Solution**: Use Drizzle or Kysely instead:\n\n```typescript\n\u002F\u002F ❌ WRONG - This doesn't exist\nimport { d1Adapter } from 'better-auth\u002Fadapters\u002Fd1'\ndatabase: d1Adapter(env.DB)\n\n\u002F\u002F ✅ CORRECT - Use Drizzle\nimport { drizzleAdapter } from 'better-auth\u002Fadapters\u002Fdrizzle'\nimport { drizzle } from 'drizzle-orm\u002Fd1'\nconst db = drizzle(env.DB, { schema })\ndatabase: drizzleAdapter(db, { provider: \"sqlite\" })\n\n\u002F\u002F ✅ CORRECT - Use Kysely\nimport { Kysely } from 'kysely'\nimport { D1Dialect } from 'kysely-d1'\ndatabase: {\n  db: new Kysely({ dialect: new D1Dialect({ database: env.DB }) }),\n  type: \"sqlite\"\n}\n```\n\n**Source**: Verified from 4 production repositories using better-auth + D1\n\n---\n\n### Issue 2: Schema Generation Fails\n\n**Problem**: `npx better-auth migrate` doesn't create D1-compatible schema.\n\n**Symptoms**: Migration SQL has wrong syntax or doesn't work with D1.\n\n**Solution**: Use Drizzle Kit to generate migrations:\n\n```bash\n# Generate migration from Drizzle schema\nnpx drizzle-kit generate\n\n# Apply to D1\nwrangler d1 migrations apply my-app-db --remote\n```\n\n**Why**: Drizzle Kit generates SQLite-compatible SQL that works with D1.\n\n---\n\n### Issue 3: \"CamelCase\" vs \"snake_case\" Column Mismatch\n\n**Problem**: Database has `email_verified` but better-auth expects `emailVerified`.\n\n**Symptoms**: Session reads fail, user data missing fields.\n\n**⚠️ CRITICAL (v1.4.10+)**: Using Kysely's `CamelCasePlugin` **breaks join parsing** in better-auth adapter. The plugin converts join keys like `_joined_user_user_id` to `_joinedUserUserId`, causing user data to be null in session queries.\n\n**Solution for Drizzle**: Define schema with camelCase from the start (as shown in examples).\n\n**Solution for Kysely with CamelCasePlugin**: Use **separate Kysely instance** without CamelCasePlugin for better-auth:\n\n```typescript\n\u002F\u002F DB for better-auth (no CamelCasePlugin)\nconst authDb = new Kysely({\n  dialect: new D1Dialect({ database: env.DB }),\n})\n\n\u002F\u002F DB for app queries (with CamelCasePlugin)\nconst appDb = new Kysely({\n  dialect: new D1Dialect({ database: env.DB }),\n  plugins: [new CamelCasePlugin()],\n})\n\nexport const auth = betterAuth({\n  database: { db: authDb, type: \"sqlite\" },\n})\n```\n\n**Source**: [GitHub Issue #7136](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7136)\n\n---\n\n### Issue 4: D1 Eventual Consistency\n\n**Problem**: Session reads immediately after write return stale data.\n\n**Symptoms**: User logs in but `getSession()` returns null on next request.\n\n**Solution**: Use Cloudflare KV for session storage (strong consistency):\n\n```typescript\nimport { betterAuth } from \"better-auth\";\n\nexport function createAuth(db: Database, env: Env) {\n  return betterAuth({\n    database: drizzleAdapter(db, { provider: \"sqlite\" }),\n    session: {\n      storage: {\n        get: async (sessionId) => {\n          const session = await env.SESSIONS_KV.get(sessionId);\n          return session ? JSON.parse(session) : null;\n        },\n        set: async (sessionId, session, ttl) => {\n          await env.SESSIONS_KV.put(sessionId, JSON.stringify(session), {\n            expirationTtl: ttl,\n          });\n        },\n        delete: async (sessionId) => {\n          await env.SESSIONS_KV.delete(sessionId);\n        },\n      },\n    },\n  });\n}\n```\n\n**Add to `wrangler.toml`**:\n```toml\n[[kv_namespaces]]\nbinding = \"SESSIONS_KV\"\nid = \"your-kv-namespace-id\"\n```\n\n---\n\n### Issue 5: CORS Errors for SPA Applications\n\n**Problem**: CORS errors when auth API is on different origin than frontend.\n\n**Symptoms**: `Access-Control-Allow-Origin` errors in browser console.\n\n**Solution**: Configure CORS headers in Worker and ensure `trustedOrigins` match:\n\n```typescript\nimport { cors } from \"hono\u002Fcors\";\n\n\u002F\u002F CRITICAL: Both must match frontend origin exactly\napp.use(\n  \"\u002Fapi\u002Fauth\u002F*\",\n  cors({\n    origin: \"http:\u002F\u002Flocalhost:5173\", \u002F\u002F Frontend URL (no trailing slash)\n    credentials: true, \u002F\u002F Allow cookies\n    allowMethods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\"],\n  })\n);\n\n\u002F\u002F And in better-auth config\nexport const auth = betterAuth({\n  trustedOrigins: [\"http:\u002F\u002Flocalhost:5173\"], \u002F\u002F Same as CORS origin\n  \u002F\u002F ...\n});\n```\n\n**Common Mistakes**:\n- Typo in origin URL (trailing slash, http vs https, wrong port)\n- Mismatched origins between CORS config and `trustedOrigins`\n- CORS middleware registered AFTER auth routes (must be before)\n\n**Source**: [GitHub Issue #7434](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7434)\n\n---\n\n### Issue 6: OAuth Redirect URI Mismatch\n\n**Problem**: Social sign-in fails with \"redirect_uri_mismatch\" error.\n\n**Symptoms**: Google\u002FGitHub OAuth returns error after user consent.\n\n**Solution**: Ensure exact match in OAuth provider settings:\n\n```\nProvider setting: https:\u002F\u002Fyourdomain.com\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle\nbetter-auth URL:  https:\u002F\u002Fyourdomain.com\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle\n\n❌ Wrong: http vs https, trailing slash, subdomain mismatch\n✅ Right: Exact character-for-character match\n```\n\n**Check better-auth callback URL**:\n```typescript\n\u002F\u002F It's always: {baseURL}\u002Fapi\u002Fauth\u002Fcallback\u002F{provider}\nconst callbackURL = `${env.BETTER_AUTH_URL}\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle`;\nconsole.log(\"Configure this URL in Google Console:\", callbackURL);\n```\n\n---\n\n### Issue 7: Missing Dependencies\n\n**Problem**: TypeScript errors or runtime errors about missing packages.\n\n**Symptoms**: `Cannot find module 'drizzle-orm'` or similar.\n\n**Solution**: Install all required packages:\n\n**For Drizzle approach**:\n```bash\nnpm install better-auth drizzle-orm drizzle-kit @cloudflare\u002Fworkers-types\n```\n\n**For Kysely approach**:\n```bash\nnpm install better-auth kysely kysely-d1 @cloudflare\u002Fworkers-types\n```\n\n---\n\n### Issue 8: Email Verification Not Sending\n\n**Problem**: Email verification links never arrive.\n\n**Symptoms**: User signs up, but no email received.\n\n**Solution**: Implement `sendVerificationEmail` handler:\n\n```typescript\nexport const auth = betterAuth({\n  database: \u002F* ... *\u002F,\n  emailAndPassword: {\n    enabled: true,\n    requireEmailVerification: true,\n  },\n  emailVerification: {\n    sendVerificationEmail: async ({ user, url }) => {\n      \u002F\u002F Use your email service (SendGrid, Resend, etc.)\n      await sendEmail({\n        to: user.email,\n        subject: \"Verify your email\",\n        html: `\n          \u003Cp>Click the link below to verify your email:\u003C\u002Fp>\n          \u003Ca href=\"${url}\">Verify Email\u003C\u002Fa>\n        `,\n      });\n    },\n    sendOnSignUp: true,\n    autoSignInAfterVerification: true,\n    expiresIn: 3600, \u002F\u002F 1 hour\n  },\n});\n```\n\n**For Cloudflare**: Use Cloudflare Email Routing or external service (Resend, SendGrid).\n\n---\n\n### Issue 9: Session Expires Too Quickly\n\n**Problem**: Session expires unexpectedly or never expires.\n\n**Symptoms**: User logged out unexpectedly or session persists after logout.\n\n**Solution**: Configure session expiration:\n\n```typescript\nexport const auth = betterAuth({\n  database: \u002F* ... *\u002F,\n  session: {\n    expiresIn: 60 * 60 * 24 * 7, \u002F\u002F 7 days (in seconds)\n    updateAge: 60 * 60 * 24, \u002F\u002F Update session every 24 hours\n  },\n});\n```\n\n---\n\n### Issue 10: Social Provider Missing User Data\n\n**Problem**: Social sign-in succeeds but missing user data (name, avatar).\n\n**Symptoms**: `session.user.name` is null after Google\u002FGitHub sign-in.\n\n**Solution**: Request additional scopes:\n\n```typescript\nsocialProviders: {\n  google: {\n    clientId: env.GOOGLE_CLIENT_ID,\n    clientSecret: env.GOOGLE_CLIENT_SECRET,\n    scope: [\"openid\", \"email\", \"profile\"], \u002F\u002F Include 'profile' for name\u002Fimage\n  },\n  github: {\n    clientId: env.GITHUB_CLIENT_ID,\n    clientSecret: env.GITHUB_CLIENT_SECRET,\n    scope: [\"user:email\", \"read:user\"], \u002F\u002F 'read:user' for full profile\n  },\n}\n```\n\n---\n\n### Issue 11: TypeScript Errors with Drizzle Schema\n\n**Problem**: TypeScript complains about schema types.\n\n**Symptoms**: `Type 'DrizzleD1Database' is not assignable to...`\n\n**Solution**: Export proper types from database:\n\n```typescript\n\u002F\u002F src\u002Fdb\u002Findex.ts\nimport { drizzle, type DrizzleD1Database } from \"drizzle-orm\u002Fd1\";\nimport * as schema from \".\u002Fschema\";\n\nexport type Database = DrizzleD1Database\u003Ctypeof schema>;\n\nexport function createDatabase(d1: D1Database): Database {\n  return drizzle(d1, { schema });\n}\n```\n\n---\n\n### Issue 12: Wrangler Dev Mode Not Working\n\n**Problem**: `wrangler dev` fails with database errors.\n\n**Symptoms**: \"Database not found\" or migration errors in local dev.\n\n**Solution**: Apply migrations locally first:\n\n```bash\n# Apply migrations to local D1\nwrangler d1 migrations apply my-app-db --local\n\n# Then run dev server\nwrangler dev\n```\n\n---\n\n### Issue 13: User Data Updates Not Reflecting in UI (with TanStack Query)\n\n**Problem**: After updating user data (e.g., avatar, name), changes don't appear in `useSession()` despite calling `queryClient.invalidateQueries()`.\n\n**Symptoms**: Avatar image or user profile data appears stale after successful update. TanStack Query cache shows updated data, but better-auth session still shows old values.\n\n**Root Cause**: better-auth uses **nanostores** for session state management, not TanStack Query. Calling `queryClient.invalidateQueries()` only invalidates React Query cache, not the better-auth nanostore.\n\n**Solution**: Manually notify the nanostore after updating user data:\n\n```typescript\n\u002F\u002F Update user data\nconst { data, error } = await authClient.updateUser({\n  image: newAvatarUrl,\n  name: newName\n})\n\nif (!error) {\n  \u002F\u002F Manually invalidate better-auth session state\n  authClient.$store.notify('$sessionSignal')\n\n  \u002F\u002F Optional: Also invalidate React Query if using it for other data\n  queryClient.invalidateQueries({ queryKey: ['user-profile'] })\n}\n```\n\n**When to use**:\n- Using better-auth + TanStack Query together\n- Updating user profile fields (name, image, email)\n- Any operation that modifies session user data client-side\n\n**Alternative**: Call `refetch()` from `useSession()`, but `$store.notify()` is more direct:\n\n```typescript\nconst { data: session, refetch } = authClient.useSession()\n\u002F\u002F After update\nawait refetch()\n```\n\n**Note**: `$store` is an undocumented internal API. This pattern is production-validated but may change in future better-auth versions.\n\n**Source**: Community-discovered pattern, production use verified\n\n---\n\n### Issue 14: apiKey Table Schema Mismatch with D1\n\n**Problem**: better-auth CLI (`npx @better-auth\u002Fcli generate`) fails with \"Failed to initialize database adapter\" when using D1.\n\n**Symptoms**: CLI cannot connect to D1 to introspect schema. Running migrations through CLI doesn't work.\n\n**Root Cause**: The CLI expects a direct SQLite connection, but D1 requires Cloudflare's binding API.\n\n**Solution**: Skip the CLI and create migrations manually using the documented apiKey schema:\n\n```sql\nCREATE TABLE api_key (\n  id TEXT PRIMARY KEY NOT NULL,\n  user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,\n  name TEXT,\n  start TEXT,\n  prefix TEXT,\n  key TEXT NOT NULL,\n  enabled INTEGER DEFAULT 1,\n  rate_limit_enabled INTEGER,\n  rate_limit_time_window INTEGER,\n  rate_limit_max INTEGER,\n  request_count INTEGER DEFAULT 0,\n  last_request INTEGER,\n  remaining INTEGER,\n  refill_interval INTEGER,\n  refill_amount INTEGER,\n  last_refill_at INTEGER,\n  expires_at INTEGER,\n  permissions TEXT,\n  metadata TEXT,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL\n);\n```\n\n**Key Points**:\n- The table has exactly **21 columns** (as of better-auth v1.4+)\n- Column names use `snake_case` (e.g., `rate_limit_time_window`, not `rateLimitTimeWindow`)\n- D1 doesn't support `ALTER TABLE DROP COLUMN` - if schema drifts, use fresh migration pattern (drop and recreate tables)\n- In Drizzle adapter config, use `apikey` (lowercase) as the table name mapping\n\n**Fresh Migration Pattern for D1**:\n```sql\n-- Drop in reverse dependency order\nDROP TABLE IF EXISTS api_key;\nDROP TABLE IF EXISTS session;\n-- ... other tables\n\n-- Recreate with clean schema\nCREATE TABLE api_key (...);\n```\n\n**Source**: Production debugging with D1 + better-auth apiKey plugin\n\n---\n\n### Issue 15: Admin Plugin Requires DB Role (Dual-Auth)\n\n**Problem**: Admin plugin methods like `listUsers` fail with \"You are not allowed to list users\" even though your middleware passes.\n\n**Symptoms**: Custom `requireAdmin` middleware (checking ADMIN_EMAILS env var) passes, but `auth.api.listUsers()` returns 403.\n\n**Root Cause**: better-auth admin plugin has **two** authorization layers:\n1. **Your middleware** - Custom check (e.g., ADMIN_EMAILS)\n2. **better-auth internal** - Checks `user.role === 'admin'` in database\n\nBoth must pass for admin plugin methods to work.\n\n**Solution**: Set user role to 'admin' in the database:\n\n```sql\n-- Fix for existing users\nUPDATE user SET role = 'admin' WHERE email = 'admin@example.com';\n```\n\nOr use the admin UI\u002FAPI to set roles after initial setup.\n\n**Why**: The admin plugin's `listUsers`, `banUser`, `impersonateUser`, etc. all check `user.role` in the database, not your custom middleware logic.\n\n**Source**: Production debugging - misleading error message led to root cause discovery via `wrangler tail`\n\n---\n\n### Issue 16: Organization\u002FTeam updated_at Must Be Nullable\n\n**Problem**: Organization creation fails with SQL constraint error even though API returns \"slug already exists\".\n\n**Symptoms**:\n- Error message says \"An organization with this slug already exists\"\n- Database table is actually empty\n- `wrangler tail` shows: `Failed query: insert into \"organization\" ... values (?, ?, ?, null, null, ?, null)`\n\n**Root Cause**: better-auth inserts `null` for `updated_at` on creation (only sets it on updates). If your schema has `NOT NULL` constraint, insert fails.\n\n**Solution**: Make `updated_at` nullable in both schema and migrations:\n\n```typescript\n\u002F\u002F Drizzle schema - CORRECT\nexport const organization = sqliteTable('organization', {\n  \u002F\u002F ...\n  updatedAt: integer('updated_at', { mode: 'timestamp' }), \u002F\u002F No .notNull()\n});\n\nexport const team = sqliteTable('team', {\n  \u002F\u002F ...\n  updatedAt: integer('updated_at', { mode: 'timestamp' }), \u002F\u002F No .notNull()\n});\n```\n\n```sql\n-- Migration - CORRECT\nCREATE TABLE organization (\n  -- ...\n  updated_at INTEGER  -- No NOT NULL\n);\n```\n\n**Applies to**: `organization` and `team` tables (possibly other plugin tables)\n\n**Source**: Production debugging - `wrangler tail` revealed actual SQL error behind misleading \"slug exists\" message\n\n---\n\n### Issue 17: API Response Double-Nesting (listMembers, etc.)\n\n**Problem**: Custom API endpoints return double-nested data like `{ members: { members: [...], total: N } }`.\n\n**Symptoms**: UI shows \"undefined\" for counts, empty lists despite data existing.\n\n**Root Cause**: better-auth methods like `listMembers` return `{ members: [...], total: N }`. Wrapping with `c.json({ members: result })` creates double nesting.\n\n**Solution**: Extract the array from better-auth response:\n\n```typescript\n\u002F\u002F ❌ WRONG - Double nesting\nconst result = await auth.api.listMembers({ ... });\nreturn c.json({ members: result });\n\u002F\u002F Returns: { members: { members: [...], total: N } }\n\n\u002F\u002F ✅ CORRECT - Extract array\nconst result = await auth.api.listMembers({ ... });\nconst members = result?.members || [];\nreturn c.json({ members });\n\u002F\u002F Returns: { members: [...] }\n```\n\n**Affected methods** (return objects, not arrays):\n- `listMembers` → `{ members: [...], total: N }`\n- `listUsers` → `{ users: [...], total: N, limit: N }`\n- `listOrganizations` → `{ organizations: [...] }` (check structure)\n- `listInvitations` → `{ invitations: [...] }`\n\n**Pattern**: Always check better-auth method return types before wrapping in your API response.\n\n**Source**: Production debugging - UI showed \"undefined\" count, API inspection revealed nesting issue\n\n---\n\n### Issue 18: Expo Client fromJSONSchema Crash (v1.4.16)\n\n**Problem**: Importing `expoClient` from `@better-auth\u002Fexpo\u002Fclient` crashes with `TypeError: Cannot read property 'fromJSONSchema' of undefined` on v1.4.16.\n\n**Symptoms**: Runtime crash immediately when importing expoClient in React Native\u002FExpo apps.\n\n**Root Cause**: Regression introduced after PR #6933 (cookie-based OAuth state fix for Expo). One of 3 commits after f4a9f15 broke the build.\n\n**Solution**:\n- **Temporary**: Use continuous build at commit `f4a9f15` (pre-regression)\n- **Permanent**: Wait for fix (issue #7491 open as of 2026-01-20)\n\n```typescript\n\u002F\u002F Crashes on v1.4.16\nimport { expoClient } from '@better-auth\u002Fexpo\u002Fclient'\n\n\u002F\u002F Workaround: Use continuous build at f4a9f15\n\u002F\u002F Or wait for fix in next release\n```\n\n**Source**: [GitHub Issue #7491](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7491)\n\n---\n\n### Issue 19: additionalFields string[] Returns Stringified JSON\n\n**Problem**: After v1.4.12, `additionalFields` with `type: 'string[]'` return stringified arrays (`'[\"a\",\"b\"]'`) instead of native arrays when querying via Drizzle directly.\n\n**Symptoms**: `user.notificationTokens` is a string, not an array. Code expecting arrays breaks.\n\n**Root Cause**: In Drizzle adapter, `string[]` fields are stored with `mode: 'json'`, which expects arrays. But better-auth v1.4.4+ passes strings to Drizzle, causing double-stringification. When querying **directly via Drizzle**, the value is a string, but when using **better-auth `internalAdapter`**, a transformer correctly returns an array.\n\n**Solution**:\n1. **Use better-auth `internalAdapter`** instead of querying Drizzle directly (has transformer)\n2. **Change Drizzle schema** to `.jsonb()` for string[] fields\n3. **Manually parse** JSON strings until fixed\n\n```typescript\n\u002F\u002F Config\nadditionalFields: {\n  notificationTokens: {\n    type: 'string[]',\n    required: true,\n    input: true,\n  },\n}\n\n\u002F\u002F Create user\nnotificationTokens: ['token1', 'token2']\n\n\u002F\u002F Result in DB (when querying via Drizzle directly)\n\u002F\u002F '[\"token1\",\"token2\"]' (string, not array)\n```\n\n**Source**: [GitHub Issue #7440](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7440)\n\n---\n\n### Issue 20: additionalFields \"returned\" Property Blocks Input\n\n**Problem**: Setting `returned: false` on `additionalFields` prevents field from being saved via API, even with `input: true`.\n\n**Symptoms**: Field never saved to database when creating\u002Fupdating via API endpoints.\n\n**Root Cause**: The `returned: false` property blocks both read AND write operations, not just reads as intended. The `input: true` property should control write access independently.\n\n**Solution**:\n- Don't use `returned: false` if you need API write access\n- Write via server-side methods (`auth.api.*`) instead\n\n```typescript\n\u002F\u002F Organization plugin config\nadditionalFields: {\n  secretField: {\n    type: 'string',\n    required: true,\n    input: true,      \u002F\u002F Should allow API writes\n    returned: false,  \u002F\u002F Should only block reads, but blocks writes too\n  },\n}\n\n\u002F\u002F API request to create organization\n\u002F\u002F secretField is never saved to database\n```\n\n**Source**: [GitHub Issue #7489](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7489)\n\n---\n\n### Issue 21: freshAge Based on Creation Time, Not Activity\n\n**Problem**: `session.freshAge` checks time-since-creation, NOT recent activity. Active sessions become \"not fresh\" after `freshAge` elapses, even if used constantly.\n\n**Symptoms**: \"Fresh session required\" endpoints reject valid active sessions.\n\n**Why It Happens**: The `freshSessionMiddleware` checks `Date.now() - (session.updatedAt || session.createdAt)`, but `updatedAt` only changes when the session is refreshed based on `updateAge`. If `updateAge > freshAge`, the session becomes \"not fresh\" before `updatedAt` is bumped.\n\n**Solution**:\n1. **Set `updateAge \u003C= freshAge`** to ensure freshness is updated before expiry\n2. **Avoid \"fresh session required\"** gating for long-lived sessions\n3. **Accept as design**: freshAge is strictly time-since-creation (maintainer confirmed)\n\n```typescript\n\u002F\u002F Config\nsession: {\n  expiresIn: 60 * 60 * 24 * 7,    \u002F\u002F 7 days\n  freshAge: 60 * 60 * 24,          \u002F\u002F 24 hours\n  updateAge: 60 * 60 * 24 * 3,     \u002F\u002F 3 days (> freshAge!) ⚠️ PROBLEM\n\n  \u002F\u002F CORRECT - updateAge \u003C= freshAge\n  updateAge: 60 * 60 * 12,         \u002F\u002F 12 hours (\u003C freshAge)\n}\n\n\u002F\u002F Timeline with bad config:\n\u002F\u002F T+0h: User signs in (createdAt = now)\n\u002F\u002F T+12h: User makes requests (session active, still fresh)\n\u002F\u002F T+25h: User makes request (session active, BUT NOT FRESH - freshAge elapsed)\n\u002F\u002F Result: \"Fresh session required\" endpoints reject active session\n```\n\n**Source**: [GitHub Issue #7472](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7472)\n\n---\n\n### Issue 22: OAuth Token Endpoints Return Wrapped JSON\n\n**Problem**: OAuth 2.1 and OIDC token endpoints return `{ \"response\": { ...tokens... } }` instead of spec-compliant top-level JSON. OAuth clients expect `{ \"access_token\": \"...\", \"token_type\": \"bearer\" }` at root.\n\n**Symptoms**: OAuth clients fail with `Bearer undefined` or `invalid_token`.\n\n**Root Cause**: The endpoint pipeline returns `{ response, headers, status }` for internal use, which gets serialized directly for HTTP requests. This breaks OAuth\u002FOIDC spec requirements.\n\n**Solution**:\n- **Temporary**: Manually unwrap `.response` field on client\n- **Permanent**: Wait for fix (issue #7355 open, accepting contributions)\n\n```typescript\n\u002F\u002F Expected (spec-compliant)\n{ \"access_token\": \"...\", \"token_type\": \"bearer\", \"expires_in\": 3600 }\n\n\u002F\u002F Actual (wrapped)\n{ \"response\": { \"access_token\": \"...\", \"token_type\": \"bearer\", \"expires_in\": 3600 } }\n\n\u002F\u002F Result: OAuth clients fail to parse, send `Bearer undefined`\n```\n\n**Source**: [GitHub Issue #7355](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7355)\n\n---\n\n## Migration Guides\n\n### From Clerk\n\n**Key differences**:\n- Clerk: Third-party service → better-auth: Self-hosted\n- Clerk: Proprietary → better-auth: Open source\n- Clerk: Monthly cost → better-auth: Free\n\n**Migration steps**:\n\n1. **Export user data** from Clerk (CSV or API)\n2. **Import into better-auth database**:\n   ```typescript\n   \u002F\u002F migration script\n   const clerkUsers = await fetchClerkUsers();\n\n   for (const clerkUser of clerkUsers) {\n     await db.insert(user).values({\n       id: clerkUser.id,\n       email: clerkUser.email,\n       emailVerified: clerkUser.email_verified,\n       name: clerkUser.first_name + \" \" + clerkUser.last_name,\n       image: clerkUser.profile_image_url,\n     });\n   }\n   ```\n3. **Replace Clerk SDK** with better-auth client:\n   ```typescript\n   \u002F\u002F Before (Clerk)\n   import { useUser } from \"@clerk\u002Fnextjs\";\n   const { user } = useUser();\n\n   \u002F\u002F After (better-auth)\n   import { authClient } from \"@\u002Flib\u002Fauth-client\";\n   const { data: session } = authClient.useSession();\n   const user = session?.user;\n   ```\n4. **Update middleware** for session verification\n5. **Configure social providers** (same OAuth apps, different config)\n\n---\n\n### From Auth.js (NextAuth)\n\n**Key differences**:\n- Auth.js: Limited features → better-auth: Comprehensive (2FA, orgs, etc.)\n- Auth.js: Callbacks-heavy → better-auth: Plugin-based\n- Auth.js: Session handling varies → better-auth: Consistent\n\n**Migration steps**:\n\n1. **Database schema**: Auth.js and better-auth use similar schemas, but column names differ\n2. **Replace configuration**:\n   ```typescript\n   \u002F\u002F Before (Auth.js)\n   import NextAuth from \"next-auth\";\n   import GoogleProvider from \"next-auth\u002Fproviders\u002Fgoogle\";\n\n   export default NextAuth({\n     providers: [GoogleProvider({ \u002F* ... *\u002F })],\n   });\n\n   \u002F\u002F After (better-auth)\n   import { betterAuth } from \"better-auth\";\n\n   export const auth = betterAuth({\n     socialProviders: {\n       google: { \u002F* ... *\u002F },\n     },\n   });\n   ```\n3. **Update client hooks**:\n   ```typescript\n   \u002F\u002F Before\n   import { useSession } from \"next-auth\u002Freact\";\n\n   \u002F\u002F After\n   import { authClient } from \"@\u002Flib\u002Fauth-client\";\n   const { data: session } = authClient.useSession();\n   ```\n\n---\n\n## Additional Resources\n\n### Official Documentation\n\n- **Homepage**: https:\u002F\u002Fbetter-auth.com\n- **Introduction**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintroduction\n- **Installation**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Finstallation\n- **Basic Usage**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fbasic-usage\n\n### Core Concepts\n\n- **Session Management**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fsession-management\n- **Users & Accounts**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fusers-accounts\n- **Client SDK**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fclient\n- **Plugins System**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fplugins\n\n### Authentication Methods\n\n- **Email & Password**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fauthentication\u002Femail-password\n- **OAuth Providers**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Foauth\n\n### Plugin Documentation\n\n**Core Plugins**:\n- **2FA (Two-Factor)**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002F2fa\n- **Organization**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Forganization\n- **Admin**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fadmin\n- **Multi-Session**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmulti-session\n- **API Key**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fapi-key\n- **Generic OAuth**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fgeneric-oauth\n\n**Passwordless Plugins**:\n- **Passkey**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fpasskey\n- **Magic Link**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmagic-link\n- **Email OTP**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Femail-otp\n- **Phone Number**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fphone-number\n- **Anonymous**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fanonymous\n\n**Advanced Plugins**:\n- **Username**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fusername\n- **JWT**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fjwt\n- **OpenAPI**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fopen-api\n- **OIDC Provider**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Foidc-provider\n- **SSO**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fsso\n- **Stripe**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fstripe\n- **MCP**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmcp\n\n### Framework Integrations\n\n- **TanStack Start**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Ftanstack\n- **Expo (React Native)**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Fexpo\n\n### Community & Support\n\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth (22.4k ⭐)\n- **Examples**: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Ftree\u002Fmain\u002Fexamples\n- **Discord**: https:\u002F\u002Fdiscord.gg\u002Fbetter-auth\n- **Changelog**: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Freleases\n\n### Related Documentation\n\n- **Drizzle ORM**: https:\u002F\u002Form.drizzle.team\u002Fdocs\u002Fget-started-sqlite\n- **Kysely**: https:\u002F\u002Fkysely.dev\u002F\n\n---\n\n## Production Examples\n\n**Verified working D1 repositories** (all use Drizzle or Kysely):\n\n1. **zpg6\u002Fbetter-auth-cloudflare** - Drizzle + D1 (includes CLI)\n2. **zwily\u002Fexample-react-router-cloudflare-d1-drizzle-better-auth** - Drizzle + D1\n3. **foxlau\u002Freact-router-v7-better-auth** - Drizzle + D1\n4. **matthewlynch\u002Fbetter-auth-react-router-cloudflare-d1** - Kysely + D1\n\n**None** use a direct `d1Adapter` - all require Drizzle\u002FKysely.\n\n---\n\n## Version Compatibility\n\n**Tested with**:\n- `better-auth@1.4.10`\n- `drizzle-orm@0.45.1`\n- `drizzle-kit@0.31.8`\n- `kysely@0.28.9`\n- `kysely-d1@0.4.0`\n- `@cloudflare\u002Fworkers-types@latest`\n- `hono@4.11.3`\n- Node.js 18+, Bun 1.0+\n\n**Breaking changes**:\n- v1.4.6: `allowImpersonatingAdmins` defaults to `false`\n- v1.4.0: ESM-only (no CommonJS)\n- v1.3.0: Multi-team table structure change\n\nCheck changelog: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Freleases\n\n---\n\n## Community Resources\n\n**Cloudflare-specific guides:**\n- [zpg6\u002Fbetter-auth-cloudflare](https:\u002F\u002Fgithub.com\u002Fzpg6\u002Fbetter-auth-cloudflare) - Drizzle + D1 reference\n- [Hono + better-auth on Cloudflare](https:\u002F\u002Fhono.dev\u002Fexamples\u002Fbetter-auth-on-cloudflare) - Official Hono example\n- [React Router + Cloudflare D1](https:\u002F\u002Fdev.to\u002Fatman33\u002Fsetup-better-auth-with-react-router-cloudflare-d1-2ad4) - React Router v7 guide\n- [SvelteKit + Cloudflare D1](https:\u002F\u002Fmedium.com\u002F@dasfacc\u002Fsveltekit-better-auth-using-cloudflare-d1-and-drizzle-91d9d9a6d0b4) - SvelteKit guide\n\n---\n\n**Token Efficiency**:\n- **Without skill**: ~35,000 tokens (D1 adapter errors, 15+ plugins, rate limiting, session caching, database hooks, mobile integration)\n- **With skill**: ~8,000 tokens (focused on errors + patterns + all plugins + API reference)\n- **Savings**: ~77% (~27,000 tokens)\n\n**Errors prevented**: 22 documented issues with exact solutions\n**Key value**: D1 adapter requirement, nodejs_compat flag, OAuth 2.1 Provider, Bearer\u002FOneTap\u002FSCIM\u002FAnonymous plugins, rate limiting, session caching, database hooks, Expo integration, 80+ endpoint reference, additionalFields bugs, freshAge behavior, OAuth token wrapping\n\n---\n\n**Last verified**: 2026-01-21 | **Skill version**: 5.1.0 | **Changes**: Added 5 new issues from post-training-cutoff research (Expo fromJSONSchema crash, additionalFields string[] bug, additionalFields returned property bug, freshAge not activity-based, OAuth token wrapping). Expanded Issue #3 with Kysely CamelCasePlugin join parsing failure. Expanded Issue #5 with Hono CORS pattern. Added Cloudflare Workers DB binding constraints note. Added TanStack Start session nullability pattern. Updated to v1.4.16.\n","# better-auth - D1 Adapter & Error Prevention Guide\n\n**Package**: better-auth@1.4.16 (Jan 21, 2026)\n**Breaking Changes**: ESM-only (v1.4.0), Admin impersonation prevention default (v1.4.6), Multi-team table changes (v1.3), D1 requires Drizzle\u002FKysely (no direct adapter)\n\n---\n\n## ⚠️ CRITICAL: D1 Adapter Requirement\n\nbetter-auth **DOES NOT** have `d1Adapter()`. You **MUST** use:\n- **Drizzle ORM** (recommended): `drizzleAdapter(db, { provider: \"sqlite\" })`\n- **Kysely**: `new Kysely({ dialect: new D1Dialect({ database: env.DB }) })`\n\nSee Issue #1 below for details.\n\n---\n\n## What's New in v1.4.10 (Dec 31, 2025)\n\n**Major Features:**\n- **OAuth 2.1 Provider plugin** - Build your own OAuth provider (replaces MCP plugin)\n- **Patreon OAuth provider** - Social sign-in with Patreon\n- **Kick OAuth provider** - With refresh token support\n- **Vercel OAuth provider** - Sign in with Vercel\n- **Global `backgroundTasks` config** - Deferred actions for better performance\n- **Form data support** - Email authentication with fetch metadata fallback\n- **Stripe enhancements** - Flexible subscription lifecycle, `disableRedirect` option\n\n**Admin Plugin Updates:**\n- ⚠️ **Breaking**: Impersonation of admins disabled by default (v1.4.6)\n- Support role with permission-based user updates\n- Role type inference improvements\n\n**Security Fixes:**\n- SAML XML parser hardening with configurable size constraints\n- SAML assertion timestamp validation with per-provider clock skew\n- SSO domain-verified provider trust\n- Deprecated algorithm rejection\n- Line nonce enforcement\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fchangelogs\n\n---\n\n## What's New in v1.4.0 (Nov 22, 2025)\n\n**Major Features:**\n- **Stateless session management** - Sessions without database storage\n- **ESM-only package** ⚠️ Breaking: CommonJS no longer supported\n- **JWT key rotation** - Automatic key rotation for enhanced security\n- **SCIM provisioning** - Enterprise user provisioning protocol\n- **@standard-schema\u002Fspec** - Replaces ZodType for validation\n- **CaptchaFox integration** - Built-in CAPTCHA support\n- Automatic server-side IP detection\n- Cookie-based account data storage\n- Multiple passkey origins support\n- RP-Initiated Logout endpoint (OIDC)\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fchangelogs\n\n---\n\n## What's New in v1.3 (July 2025)\n\n**Major Features:**\n- **SSO with SAML 2.0** - Enterprise single sign-on (moved to separate `@better-auth\u002Fsso` package)\n- **Multi-team support** ⚠️ Breaking: `teamId` removed from member table, new `teamMembers` table required\n- **Additional fields** - Custom fields for organization\u002Fmember\u002Finvitation models\n- Performance improvements and bug fixes\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fblog\u002F1-3\n\n---\n\n## Alternative: Kysely Adapter Pattern\n\nIf you prefer Kysely over Drizzle:\n\n**File**: `src\u002Fauth.ts`\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { Kysely, CamelCasePlugin } from \"kysely\";\nimport { D1Dialect } from \"kysely-d1\";\n\ntype Env = {\n  DB: D1Database;\n  BETTER_AUTH_SECRET: string;\n  \u002F\u002F ... other env vars\n};\n\nexport function createAuth(env: Env) {\n  return betterAuth({\n    secret: env.BETTER_AUTH_SECRET,\n\n    \u002F\u002F Kysely with D1Dialect\n    database: {\n      db: new Kysely({\n        dialect: new D1Dialect({\n          database: env.DB,\n        }),\n        plugins: [\n          \u002F\u002F CRITICAL: Required if using Drizzle schema with snake_case\n          new CamelCasePlugin(),\n        ],\n      }),\n      type: \"sqlite\",\n    },\n\n    emailAndPassword: {\n      enabled: true,\n    },\n\n    \u002F\u002F ... other config\n  });\n}\n```\n\n**Why CamelCasePlugin?**\n\nIf your Drizzle schema uses `snake_case` column names (e.g., `email_verified`), but better-auth expects `camelCase` (e.g., `emailVerified`), the `CamelCasePlugin` automatically converts between the two.\n\n**⚠️ Cloudflare Workers Note**: D1 database bindings are only available inside the request handler (the `fetch()` function). You cannot initialize better-auth outside the request context. Use a factory function pattern:\n\n```typescript\n\u002F\u002F ❌ WRONG - DB binding not available outside request\nconst db = drizzle(env.DB, { schema }) \u002F\u002F env.DB doesn't exist here\nexport const auth = betterAuth({ database: drizzleAdapter(db, { provider: \"sqlite\" }) })\n\n\u002F\u002F ✅ CORRECT - Create auth instance per-request\nexport default {\n  fetch(request, env, ctx) {\n    const db = drizzle(env.DB, { schema })\n    const auth = betterAuth({ database: drizzleAdapter(db, { provider: \"sqlite\" }) })\n    return auth.handler(request)\n  }\n}\n```\n\n**Community Validation**: Multiple production implementations confirm this pattern (Medium, AnswerOverflow, official Hono examples).\n\n---\n\n## Framework Integrations\n\n### TanStack Start\n\n**⚠️ CRITICAL**: TanStack Start requires the `reactStartCookies` plugin to handle cookie setting properly.\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { drizzleAdapter } from \"better-auth\u002Fadapters\u002Fdrizzle\";\nimport { reactStartCookies } from \"better-auth\u002Freact-start\";\n\nexport const auth = betterAuth({\n  database: drizzleAdapter(db, { provider: \"sqlite\" }),\n  plugins: [\n    twoFactor(),\n    organization(),\n    reactStartCookies(), \u002F\u002F ⚠️ MUST be LAST plugin\n  ],\n});\n```\n\n**Why it's needed**: TanStack Start uses a special cookie handling system. Without this plugin, auth functions like `signInEmail()` and `signUpEmail()` won't set cookies properly, causing authentication to fail.\n\n**Important**: The `reactStartCookies` plugin **must be the last plugin in the array**.\n\n**Session Nullability Pattern**: When using `useSession()` in TanStack Start, the session object always exists, but `session.user` and `session.session` are `null` when not logged in:\n\n```typescript\nconst { data: session } = authClient.useSession()\n\n\u002F\u002F When NOT logged in:\nconsole.log(session) \u002F\u002F { user: null, session: null }\nconsole.log(!!session) \u002F\u002F true (unexpected!)\n\n\u002F\u002F Correct check:\nif (session?.user) {\n  \u002F\u002F User is logged in\n}\n```\n\n**Always check `session?.user` or `session?.session`, not just `session`**. This is expected behavior (session object container always exists).\n\n**API Route Setup** (`\u002Fsrc\u002Froutes\u002Fapi\u002Fauth\u002F$.ts`):\n```typescript\nimport { auth } from '@\u002Flib\u002Fauth'\nimport { createFileRoute } from '@tanstack\u002Freact-router'\n\nexport const Route = createFileRoute('\u002Fapi\u002Fauth\u002F$')({\n  server: {\n    handlers: {\n      GET: ({ request }) => auth.handler(request),\n      POST: ({ request }) => auth.handler(request),\n    },\n  },\n})\n```\n\n? **Official Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Ftanstack\n\n---\n\n## Available Plugins (v1.4+)\n\nBetter Auth provides plugins for advanced authentication features:\n\n| Plugin | Import | Description | Docs |\n|--------|--------|-------------|------|\n| **OAuth 2.1 Provider** | `better-auth\u002Fplugins` | Build OAuth 2.1 provider with PKCE, JWT tokens, consent flows (replaces MCP & OIDC plugins) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Foauth-provider) |\n| **SSO** | `better-auth\u002Fplugins` | Enterprise Single Sign-On with OIDC, OAuth2, and SAML 2.0 support | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fsso) |\n| **Stripe** | `better-auth\u002Fplugins` | Payment and subscription management with flexible lifecycle handling | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fstripe) |\n| **MCP** | `better-auth\u002Fplugins` | ⚠️ **Deprecated** - Use OAuth 2.1 Provider instead | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmcp) |\n| **Expo** | `better-auth\u002Fexpo` | React Native\u002FExpo with `webBrowserOptions` and last-login-method tracking | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Fexpo) |\n\n### OAuth 2.1 Provider Plugin (New in v1.4.9)\n\nBuild your own OAuth provider for MCP servers, third-party apps, or API access:\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { oauthProvider } from \"better-auth\u002Fplugins\";\nimport { jwt } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  plugins: [\n    jwt(), \u002F\u002F Required for token signing\n    oauthProvider({\n      \u002F\u002F Token expiration (seconds)\n      accessTokenExpiresIn: 3600,      \u002F\u002F 1 hour\n      refreshTokenExpiresIn: 2592000,  \u002F\u002F 30 days\n      authorizationCodeExpiresIn: 600, \u002F\u002F 10 minutes\n    }),\n  ],\n});\n```\n\n**Key Features:**\n- **OAuth 2.1 compliant** - PKCE mandatory, S256 only, no implicit flow\n- **Three grant types**: `authorization_code`, `refresh_token`, `client_credentials`\n- **JWT or opaque tokens** - Configurable token format\n- **Dynamic client registration** - RFC 7591 compliant\n- **Consent management** - Skip consent for trusted clients\n- **OIDC UserInfo endpoint** - `\u002Foauth2\u002Fuserinfo` with scope-based claims\n\n**Required Well-Known Endpoints:**\n\n```typescript\n\u002F\u002F app\u002Fapi\u002F.well-known\u002Foauth-authorization-server\u002Froute.ts\nexport async function GET() {\n  return Response.json({\n    issuer: process.env.BETTER_AUTH_URL,\n    authorization_endpoint: `${process.env.BETTER_AUTH_URL}\u002Fapi\u002Fauth\u002Foauth2\u002Fauthorize`,\n    token_endpoint: `${process.env.BETTER_AUTH_URL}\u002Fapi\u002Fauth\u002Foauth2\u002Ftoken`,\n    \u002F\u002F ... other metadata\n  });\n}\n```\n\n**Create OAuth Client:**\n\n```typescript\nconst client = await auth.api.createOAuthClient({\n  body: {\n    name: \"My MCP Server\",\n    redirectURLs: [\"https:\u002F\u002Fclaude.ai\u002Fcallback\"],\n    type: \"public\", \u002F\u002F or \"confidential\"\n  },\n});\n\u002F\u002F Returns: { clientId, clientSecret (if confidential) }\n```\n\n? **Full Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Foauth-provider\n\n⚠️ **Note**: This plugin is in active development and may not be suitable for production use yet.\n\n---\n\n### Additional Plugins Reference\n\n| Plugin | Description | Docs |\n|--------|-------------|------|\n| **Bearer** | API token auth (alternative to cookies for APIs) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fbearer) |\n| **One Tap** | Google One Tap frictionless sign-in | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fone-tap) |\n| **SCIM** | Enterprise user provisioning (SCIM 2.0) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fscim) |\n| **Anonymous** | Guest user access without PII | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fanonymous) |\n| **Username** | Username-based sign-in (alternative to email) | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fusername) |\n| **Generic OAuth** | Custom OAuth providers with PKCE | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fgeneric-oauth) |\n| **Multi-Session** | Multiple accounts in same browser | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmulti-session) |\n| **API Key** | Token-based auth with rate limits | [?](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fapi-key) |\n\n#### Bearer Token Plugin\n\nFor API-only authentication (mobile apps, CLI tools, third-party integrations):\n\n```typescript\nimport { bearer } from \"better-auth\u002Fplugins\";\nimport { bearerClient } from \"better-auth\u002Fclient\u002Fplugins\";\n\n\u002F\u002F Server\nexport const auth = betterAuth({\n  plugins: [bearer()],\n});\n\n\u002F\u002F Client - Store token after sign-in\nconst { token } = await authClient.signIn.email({ email, password });\nlocalStorage.setItem(\"auth_token\", token);\n\n\u002F\u002F Client - Configure fetch to include token\nconst authClient = createAuthClient({\n  plugins: [bearerClient()],\n  fetchOptions: {\n    auth: { type: \"Bearer\", token: () => localStorage.getItem(\"auth_token\") },\n  },\n});\n```\n\n#### Google One Tap Plugin\n\nFrictionless single-tap sign-in for users already signed into Google:\n\n```typescript\nimport { oneTap } from \"better-auth\u002Fplugins\";\nimport { oneTapClient } from \"better-auth\u002Fclient\u002Fplugins\";\n\n\u002F\u002F Server\nexport const auth = betterAuth({\n  plugins: [oneTap()],\n});\n\n\u002F\u002F Client\nauthClient.oneTap({\n  onSuccess: (session) => {\n    window.location.href = \"\u002Fdashboard\";\n  },\n});\n```\n\n**Requirement**: Configure authorized JavaScript origins in Google Cloud Console.\n\n#### Anonymous Plugin\n\nGuest access without requiring email\u002Fpassword:\n\n```typescript\nimport { anonymous } from \"better-auth\u002Fplugins\";\n\n\u002F\u002F Server\nexport const auth = betterAuth({\n  plugins: [\n    anonymous({\n      emailDomainName: \"anon.example.com\", \u002F\u002F temp@{id}.anon.example.com\n      onLinkAccount: async ({ anonymousUser, newUser }) => {\n        \u002F\u002F Migrate anonymous user data to linked account\n        await migrateUserData(anonymousUser.id, newUser.id);\n      },\n    }),\n  ],\n});\n\n\u002F\u002F Client\nawait authClient.signIn.anonymous();\n\u002F\u002F Later: user can link to real account via signIn.social\u002Femail\n```\n\n#### Generic OAuth Plugin\n\nAdd custom OAuth providers not in the built-in list:\n\n```typescript\nimport { genericOAuth } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  plugins: [\n    genericOAuth({\n      config: [\n        {\n          providerId: \"linear\",\n          clientId: env.LINEAR_CLIENT_ID,\n          clientSecret: env.LINEAR_CLIENT_SECRET,\n          discoveryUrl: \"https:\u002F\u002Flinear.app\u002F.well-known\u002Fopenid-configuration\",\n          scopes: [\"openid\", \"email\", \"profile\"],\n          pkce: true, \u002F\u002F Recommended\n        },\n      ],\n    }),\n  ],\n});\n```\n\n**Callback URL pattern**: `{baseURL}\u002Fapi\u002Fauth\u002Foauth2\u002Fcallback\u002F{providerId}`\n\n---\n\n## Rate Limiting\n\nBuilt-in rate limiting with customizable rules:\n\n```typescript\nexport const auth = betterAuth({\n  rateLimit: {\n    window: 60,  \u002F\u002F seconds (default: 60)\n    max: 100,    \u002F\u002F requests per window (default: 100)\n\n    \u002F\u002F Custom rules for sensitive endpoints\n    customRules: {\n      \"\u002Fsign-in\u002Femail\": { window: 10, max: 3 },\n      \"\u002Ftwo-factor\u002F*\": { window: 10, max: 3 },\n      \"\u002Fforget-password\": { window: 60, max: 5 },\n    },\n\n    \u002F\u002F Use Redis\u002FKV for distributed systems\n    storage: \"secondary-storage\", \u002F\u002F or \"database\"\n  },\n\n  \u002F\u002F Secondary storage for rate limiting\n  secondaryStorage: {\n    get: async (key) => env.KV.get(key),\n    set: async (key, value, ttl) => env.KV.put(key, value, { expirationTtl: ttl }),\n    delete: async (key) => env.KV.delete(key),\n  },\n});\n```\n\n**Note**: Server-side calls via `auth.api.*` bypass rate limiting.\n\n---\n\n## Stateless Sessions (v1.4.0+)\n\nStore sessions entirely in signed cookies without database storage:\n\n```typescript\nexport const auth = betterAuth({\n  session: {\n    \u002F\u002F Stateless: No database storage, session lives in cookie only\n    storage: undefined, \u002F\u002F or omit entirely\n\n    \u002F\u002F Cookie configuration\n    cookieCache: {\n      enabled: true,\n      maxAge: 60 * 60 * 24 * 7, \u002F\u002F 7 days\n      encoding: \"jwt\", \u002F\u002F Use JWT for stateless (not \"compact\")\n    },\n\n    \u002F\u002F Session expiration\n    expiresIn: 60 * 60 * 24 * 7, \u002F\u002F 7 days\n  },\n});\n```\n\n**When to Use:**\n\n| Storage Type | Use Case | Tradeoffs |\n|--------------|----------|-----------|\n| **Stateless (cookie-only)** | Read-heavy apps, edge\u002Fserverless, no revocation needed | Can't revoke sessions, limited payload size |\n| **D1 Database** | Full session management, audit trails, revocation | Eventual consistency issues |\n| **KV Storage** | Strong consistency, high read performance | Extra binding setup |\n\n**Key Points:**\n- Stateless sessions can't be revoked (user must wait for expiry)\n- Cookie size limit ~4KB (limits session data)\n- Use `encoding: \"jwt\"` for interoperability, `\"jwe\"` for encrypted\n- Server must have consistent `BETTER_AUTH_SECRET` across all instances\n\n---\n\n## JWT Key Rotation (v1.4.0+)\n\nAutomatically rotate JWT signing keys for enhanced security:\n\n```typescript\nimport { jwt } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  plugins: [\n    jwt({\n      \u002F\u002F Key rotation (optional, enterprise security)\n      keyRotation: {\n        enabled: true,\n        rotationInterval: 60 * 60 * 24 * 30, \u002F\u002F Rotate every 30 days\n        keepPreviousKeys: 3, \u002F\u002F Keep 3 old keys for validation\n      },\n\n      \u002F\u002F Custom signing algorithm (default: HS256)\n      algorithm: \"RS256\", \u002F\u002F Requires asymmetric keys\n\n      \u002F\u002F JWKS endpoint (auto-generated at \u002Fapi\u002Fauth\u002Fjwks)\n      exposeJWKS: true,\n    }),\n  ],\n});\n```\n\n**Key Points:**\n- Key rotation prevents compromised key from having indefinite validity\n- Old keys are kept temporarily to validate existing tokens\n- JWKS endpoint at `\u002Fapi\u002Fauth\u002Fjwks` for external services\n- Use RS256 for public key verification (microservices)\n- HS256 (default) for single-service apps\n\n---\n\n## Provider Scopes Reference\n\nCommon OAuth providers and the scopes needed for user data:\n\n| Provider | Scope | Returns |\n|----------|-------|---------|\n| **Google** | `openid` | User ID only |\n| | `email` | Email address, email_verified |\n| | `profile` | Name, avatar (picture), locale |\n| **GitHub** | `user:email` | Email address (may be private) |\n| | `read:user` | Name, avatar, profile URL, bio |\n| **Microsoft** | `openid` | User ID only |\n| | `email` | Email address |\n| | `profile` | Name, locale |\n| | `User.Read` | Full profile from Graph API |\n| **Discord** | `identify` | Username, avatar, discriminator |\n| | `email` | Email address |\n| **Apple** | `name` | First\u002Flast name (first auth only) |\n| | `email` | Email or relay address |\n| **Patreon** | `identity` | User ID, name |\n| | `identity[email]` | Email address |\n| **Vercel** | (auto) | Email, name, avatar |\n\n**Configuration Example:**\n\n```typescript\nsocialProviders: {\n  google: {\n    clientId: env.GOOGLE_CLIENT_ID,\n    clientSecret: env.GOOGLE_CLIENT_SECRET,\n    scope: [\"openid\", \"email\", \"profile\"], \u002F\u002F All user data\n  },\n  github: {\n    clientId: env.GITHUB_CLIENT_ID,\n    clientSecret: env.GITHUB_CLIENT_SECRET,\n    scope: [\"user:email\", \"read:user\"], \u002F\u002F Email + full profile\n  },\n  microsoft: {\n    clientId: env.MS_CLIENT_ID,\n    clientSecret: env.MS_CLIENT_SECRET,\n    scope: [\"openid\", \"email\", \"profile\", \"User.Read\"],\n  },\n}\n```\n\n---\n\n## Session Cookie Caching\n\nThree encoding strategies for session cookies:\n\n| Strategy | Format | Use Case |\n|----------|--------|----------|\n| **Compact** (default) | Base64url + HMAC-SHA256 | Smallest, fastest |\n| **JWT** | Standard JWT | Interoperable |\n| **JWE** | A256CBC-HS512 encrypted | Most secure |\n\n```typescript\nexport const auth = betterAuth({\n  session: {\n    cookieCache: {\n      enabled: true,\n      maxAge: 300, \u002F\u002F 5 minutes\n      encoding: \"compact\", \u002F\u002F or \"jwt\" or \"jwe\"\n    },\n    freshAge: 60 * 60 * 24, \u002F\u002F 1 day - operations requiring fresh session\n  },\n});\n```\n\n**Fresh sessions**: Some sensitive operations require recently created sessions. Configure `freshAge` to control this window.\n\n---\n\n## New Social Providers (v1.4.9+)\n\n```typescript\nsocialProviders: {\n  \u002F\u002F Patreon - Creator economy\n  patreon: {\n    clientId: env.PATREON_CLIENT_ID,\n    clientSecret: env.PATREON_CLIENT_SECRET,\n    scope: [\"identity\", \"identity[email]\"],\n  },\n\n  \u002F\u002F Kick - Streaming platform (with refresh tokens)\n  kick: {\n    clientId: env.KICK_CLIENT_ID,\n    clientSecret: env.KICK_CLIENT_SECRET,\n  },\n\n  \u002F\u002F Vercel - Developer platform\n  vercel: {\n    clientId: env.VERCEL_CLIENT_ID,\n    clientSecret: env.VERCEL_CLIENT_SECRET,\n  },\n}\n```\n\n---\n\n## Cloudflare Workers Requirements\n\n**⚠️ CRITICAL**: Cloudflare Workers require AsyncLocalStorage support:\n\n```toml\n# wrangler.toml\ncompatibility_flags = [\"nodejs_compat\"]\n# or for older Workers:\n# compatibility_flags = [\"nodejs_als\"]\n```\n\nWithout this flag, better-auth will fail with context-related errors.\n\n---\n\n## Database Hooks\n\nExecute custom logic during database operations:\n\n```typescript\nexport const auth = betterAuth({\n  databaseHooks: {\n    user: {\n      create: {\n        before: async (user, ctx) => {\n          \u002F\u002F Validate or modify before creation\n          if (user.email?.endsWith(\"@blocked.com\")) {\n            throw new APIError(\"BAD_REQUEST\", { message: \"Email domain not allowed\" });\n          }\n          return { data: { ...user, role: \"member\" } };\n        },\n        after: async (user, ctx) => {\n          \u002F\u002F Send welcome email, create related records, etc.\n          await sendWelcomeEmail(user.email);\n          await createDefaultWorkspace(user.id);\n        },\n      },\n    },\n    session: {\n      create: {\n        after: async (session, ctx) => {\n          \u002F\u002F Audit logging\n          await auditLog.create({ action: \"session_created\", userId: session.userId });\n        },\n      },\n    },\n  },\n});\n```\n\n**Available hooks**: `create`, `update` for `user`, `session`, `account`, `verification` tables.\n\n---\n\n## Expo\u002FReact Native Integration\n\nComplete mobile integration pattern:\n\n```typescript\n\u002F\u002F Client setup with secure storage\nimport { expoClient } from \"@better-auth\u002Fexpo\";\nimport * as SecureStore from \"expo-secure-store\";\n\nconst authClient = createAuthClient({\n  baseURL: \"https:\u002F\u002Fapi.example.com\",\n  plugins: [expoClient({ storage: SecureStore })],\n});\n\n\u002F\u002F OAuth with deep linking\nawait authClient.signIn.social({\n  provider: \"google\",\n  callbackURL: \"myapp:\u002F\u002Fauth\u002Fcallback\", \u002F\u002F Deep link\n});\n\n\u002F\u002F Or use ID token verification (no redirect)\nawait authClient.signIn.social({\n  provider: \"google\",\n  idToken: {\n    token: googleIdToken,\n    nonce: generatedNonce,\n  },\n});\n\n\u002F\u002F Authenticated requests\nconst cookie = await authClient.getCookie();\nawait fetch(\"https:\u002F\u002Fapi.example.com\u002Fdata\", {\n  headers: { Cookie: cookie },\n  credentials: \"omit\",\n});\n```\n\n**app.json deep link setup**:\n```json\n{\n  \"expo\": {\n    \"scheme\": \"myapp\"\n  }\n}\n```\n\n**Server trustedOrigins** (development):\n```typescript\ntrustedOrigins: [\"exp:\u002F\u002F**\", \"myapp:\u002F\u002F\"]\n```\n\n---\n\n## API Reference\n\n### Overview: What You Get For Free\n\nWhen you call `auth.handler()`, better-auth automatically exposes **80+ production-ready REST endpoints** at `\u002Fapi\u002Fauth\u002F*`. Every endpoint is also available as a **server-side method** via `auth.api.*` for programmatic use.\n\nThis dual-layer API system means:\n- **Clients** (React, Vue, mobile apps) call HTTP endpoints directly\n- **Server-side code** (middleware, background jobs) uses `auth.api.*` methods\n- **Zero boilerplate** - no need to write auth endpoints manually\n\n**Time savings**: Building this from scratch = ~220 hours. With better-auth = ~4-8 hours. **97% reduction.**\n\n---\n\n### Auto-Generated HTTP Endpoints\n\nAll endpoints are automatically exposed at `\u002Fapi\u002Fauth\u002F*` when using `auth.handler()`.\n\n#### Core Authentication Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fsign-up\u002Femail` | POST | Register with email\u002Fpassword |\n| `\u002Fsign-in\u002Femail` | POST | Authenticate with email\u002Fpassword |\n| `\u002Fsign-out` | POST | Logout user |\n| `\u002Fchange-password` | POST | Update password (requires current password) |\n| `\u002Fforget-password` | POST | Initiate password reset flow |\n| `\u002Freset-password` | POST | Complete password reset with token |\n| `\u002Fsend-verification-email` | POST | Send email verification link |\n| `\u002Fverify-email` | GET | Verify email with token (`?token=\u003Ctoken>`) |\n| `\u002Fget-session` | GET | Retrieve current session |\n| `\u002Flist-sessions` | GET | Get all active user sessions |\n| `\u002Frevoke-session` | POST | End specific session |\n| `\u002Frevoke-other-sessions` | POST | End all sessions except current |\n| `\u002Frevoke-sessions` | POST | End all user sessions |\n| `\u002Fupdate-user` | POST | Modify user profile (name, image) |\n| `\u002Fchange-email` | POST | Update email address |\n| `\u002Fset-password` | POST | Add password to OAuth-only account |\n| `\u002Fdelete-user` | POST | Remove user account |\n| `\u002Flist-accounts` | GET | Get linked authentication providers |\n| `\u002Flink-social` | POST | Connect OAuth provider to account |\n| `\u002Funlink-account` | POST | Disconnect provider |\n\n#### Social OAuth Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fsign-in\u002Fsocial` | POST | Initiate OAuth flow (provider specified in body) |\n| `\u002Fcallback\u002F:provider` | GET | OAuth callback handler (e.g., `\u002Fcallback\u002Fgoogle`) |\n| `\u002Fget-access-token` | GET | Retrieve provider access token |\n\n**Example OAuth flow**:\n```typescript\n\u002F\u002F Client initiates\nawait authClient.signIn.social({\n  provider: \"google\",\n  callbackURL: \"\u002Fdashboard\",\n});\n\n\u002F\u002F better-auth handles redirect to Google\n\u002F\u002F Google redirects back to \u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle\n\u002F\u002F better-auth creates session automatically\n```\n\n---\n\n#### Plugin Endpoints\n\n##### Two-Factor Authentication (2FA Plugin)\n\n```typescript\nimport { twoFactor } from \"better-auth\u002Fplugins\";\n```\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Ftwo-factor\u002Fenable` | POST | Activate 2FA for user |\n| `\u002Ftwo-factor\u002Fdisable` | POST | Deactivate 2FA |\n| `\u002Ftwo-factor\u002Fget-totp-uri` | GET | Get QR code URI for authenticator app |\n| `\u002Ftwo-factor\u002Fverify-totp` | POST | Validate TOTP code from authenticator |\n| `\u002Ftwo-factor\u002Fsend-otp` | POST | Send OTP via email |\n| `\u002Ftwo-factor\u002Fverify-otp` | POST | Validate email OTP |\n| `\u002Ftwo-factor\u002Fgenerate-backup-codes` | POST | Create recovery codes |\n| `\u002Ftwo-factor\u002Fverify-backup-code` | POST | Use backup code for login |\n| `\u002Ftwo-factor\u002Fview-backup-codes` | GET | View current backup codes |\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002F2fa\n\n##### Organization Plugin (Multi-Tenant SaaS)\n\n```typescript\nimport { organization } from \"better-auth\u002Fplugins\";\n```\n\n**Organizations** (10 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Fcreate` | POST | Create organization |\n| `\u002Forganization\u002Flist` | GET | List user's organizations |\n| `\u002Forganization\u002Fget-full` | GET | Get complete org details |\n| `\u002Forganization\u002Fupdate` | PUT | Modify organization |\n| `\u002Forganization\u002Fdelete` | DELETE | Remove organization |\n| `\u002Forganization\u002Fcheck-slug` | GET | Verify slug availability |\n| `\u002Forganization\u002Fset-active` | POST | Set active organization context |\n\n**Members** (8 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Flist-members` | GET | Get organization members |\n| `\u002Forganization\u002Fadd-member` | POST | Add member directly |\n| `\u002Forganization\u002Fremove-member` | DELETE | Remove member |\n| `\u002Forganization\u002Fupdate-member-role` | PUT | Change member role |\n| `\u002Forganization\u002Fget-active-member` | GET | Get current member info |\n| `\u002Forganization\u002Fleave` | POST | Leave organization |\n\n**Invitations** (7 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Finvite-member` | POST | Send invitation email |\n| `\u002Forganization\u002Faccept-invitation` | POST | Accept invite |\n| `\u002Forganization\u002Freject-invitation` | POST | Reject invite |\n| `\u002Forganization\u002Fcancel-invitation` | POST | Cancel pending invite |\n| `\u002Forganization\u002Fget-invitation` | GET | Get invitation details |\n| `\u002Forganization\u002Flist-invitations` | GET | List org invitations |\n| `\u002Forganization\u002Flist-user-invitations` | GET | List user's pending invites |\n\n**Teams** (8 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Fcreate-team` | POST | Create team within org |\n| `\u002Forganization\u002Flist-teams` | GET | List organization teams |\n| `\u002Forganization\u002Fupdate-team` | PUT | Modify team |\n| `\u002Forganization\u002Fremove-team` | DELETE | Remove team |\n| `\u002Forganization\u002Fset-active-team` | POST | Set active team context |\n| `\u002Forganization\u002Flist-team-members` | GET | List team members |\n| `\u002Forganization\u002Fadd-team-member` | POST | Add member to team |\n| `\u002Forganization\u002Fremove-team-member` | DELETE | Remove team member |\n\n**Permissions & Roles** (6 endpoints):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Forganization\u002Fhas-permission` | POST | Check if user has permission |\n| `\u002Forganization\u002Fcreate-role` | POST | Create custom role |\n| `\u002Forganization\u002Fdelete-role` | DELETE | Delete custom role |\n| `\u002Forganization\u002Flist-roles` | GET | List all roles |\n| `\u002Forganization\u002Fget-role` | GET | Get role details |\n| `\u002Forganization\u002Fupdate-role` | PUT | Modify role permissions |\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Forganization\n\n##### Admin Plugin\n\n```typescript\nimport { admin } from \"better-auth\u002Fplugins\";\n\n\u002F\u002F v1.4.10 configuration options\nadmin({\n  defaultRole: \"user\",\n  adminRoles: [\"admin\"],\n  adminUserIds: [\"user_abc123\"], \u002F\u002F Always grant admin to specific users\n  impersonationSessionDuration: 3600, \u002F\u002F 1 hour (seconds)\n  allowImpersonatingAdmins: false, \u002F\u002F ⚠️ Default changed in v1.4.6\n  defaultBanReason: \"Violation of Terms of Service\",\n  bannedUserMessage: \"Your account has been suspended\",\n})\n```\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fadmin\u002Fcreate-user` | POST | Create user as admin |\n| `\u002Fadmin\u002Flist-users` | GET | List all users (with filters\u002Fpagination) |\n| `\u002Fadmin\u002Fset-role` | POST | Assign user role |\n| `\u002Fadmin\u002Fset-user-password` | POST | Change user password |\n| `\u002Fadmin\u002Fupdate-user` | PUT | Modify user details |\n| `\u002Fadmin\u002Fremove-user` | DELETE | Delete user account |\n| `\u002Fadmin\u002Fban-user` | POST | Ban user account (with optional expiry) |\n| `\u002Fadmin\u002Funban-user` | POST | Unban user |\n| `\u002Fadmin\u002Flist-user-sessions` | GET | Get user's active sessions |\n| `\u002Fadmin\u002Frevoke-user-session` | DELETE | End specific user session |\n| `\u002Fadmin\u002Frevoke-user-sessions` | DELETE | End all user sessions |\n| `\u002Fadmin\u002Fimpersonate-user` | POST | Start impersonating user |\n| `\u002Fadmin\u002Fstop-impersonating` | POST | End impersonation session |\n\n**⚠️ Breaking Change (v1.4.6)**: `allowImpersonatingAdmins` now defaults to `false`. Set to `true` explicitly if you need admin-on-admin impersonation.\n\n**Custom Roles with Permissions (v1.4.10):**\n\n```typescript\nimport { createAccessControl } from \"better-auth\u002Fplugins\u002Faccess\";\n\n\u002F\u002F Define resources and permissions\nconst ac = createAccessControl({\n  user: [\"create\", \"read\", \"update\", \"delete\", \"ban\", \"impersonate\"],\n  project: [\"create\", \"read\", \"update\", \"delete\", \"share\"],\n} as const);\n\n\u002F\u002F Create custom roles\nconst supportRole = ac.newRole({\n  user: [\"read\", \"ban\"],      \u002F\u002F Can view and ban users\n  project: [\"read\"],          \u002F\u002F Can view projects\n});\n\nconst managerRole = ac.newRole({\n  user: [\"read\", \"update\"],\n  project: [\"create\", \"read\", \"update\", \"delete\"],\n});\n\n\u002F\u002F Use in plugin\nadmin({\n  ac,\n  roles: {\n    support: supportRole,\n    manager: managerRole,\n  },\n})\n```\n\n? **Docs**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fadmin\n\n##### Other Plugin Endpoints\n\n**Passkey Plugin** (5 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fpasskey):\n- `\u002Fpasskey\u002Fadd`, `\u002Fsign-in\u002Fpasskey`, `\u002Fpasskey\u002Flist`, `\u002Fpasskey\u002Fdelete`, `\u002Fpasskey\u002Fupdate`\n\n**Magic Link Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmagic-link):\n- `\u002Fsign-in\u002Fmagic-link`, `\u002Fmagic-link\u002Fverify`\n\n**Username Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fusername):\n- `\u002Fsign-in\u002Fusername`, `\u002Fusername\u002Fis-available`\n\n**Phone Number Plugin** (5 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fphone-number):\n- `\u002Fsign-in\u002Fphone-number`, `\u002Fphone-number\u002Fsend-otp`, `\u002Fphone-number\u002Fverify`, `\u002Fphone-number\u002Frequest-password-reset`, `\u002Fphone-number\u002Freset-password`\n\n**Email OTP Plugin** (6 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Femail-otp):\n- `\u002Femail-otp\u002Fsend-verification-otp`, `\u002Femail-otp\u002Fcheck-verification-otp`, `\u002Fsign-in\u002Femail-otp`, `\u002Femail-otp\u002Fverify-email`, `\u002Fforget-password\u002Femail-otp`, `\u002Femail-otp\u002Freset-password`\n\n**Anonymous Plugin** (1 endpoint) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fanonymous):\n- `\u002Fsign-in\u002Fanonymous`\n\n**JWT Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fjwt):\n- `\u002Ftoken` (get JWT), `\u002Fjwks` (public key for verification)\n\n**OpenAPI Plugin** (2 endpoints) - [Docs](https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fopen-api):\n- `\u002Freference` (interactive API docs with Scalar UI)\n- `\u002Fgenerate-openapi-schema` (get OpenAPI spec as JSON)\n\n---\n\n### Server-Side API Methods (`auth.api.*`)\n\nEvery HTTP endpoint has a corresponding server-side method. Use these for:\n- **Server-side middleware** (protecting routes)\n- **Background jobs** (user cleanup, notifications)\n- **Admin operations** (bulk user management)\n- **Custom auth flows** (programmatic session creation)\n\n#### Core API Methods\n\n```typescript\n\u002F\u002F Authentication\nawait auth.api.signUpEmail({\n  body: { email, password, name },\n  headers: request.headers,\n});\n\nawait auth.api.signInEmail({\n  body: { email, password, rememberMe: true },\n  headers: request.headers,\n});\n\nawait auth.api.signOut({ headers: request.headers });\n\n\u002F\u002F Session Management\nconst session = await auth.api.getSession({ headers: request.headers });\n\nawait auth.api.listSessions({ headers: request.headers });\n\nawait auth.api.revokeSession({\n  body: { token: \"session_token_here\" },\n  headers: request.headers,\n});\n\n\u002F\u002F User Management\nawait auth.api.updateUser({\n  body: { name: \"New Name\", image: \"https:\u002F\u002F...\" },\n  headers: request.headers,\n});\n\nawait auth.api.changeEmail({\n  body: { newEmail: \"newemail@example.com\" },\n  headers: request.headers,\n});\n\nawait auth.api.deleteUser({\n  body: { password: \"current_password\" },\n  headers: request.headers,\n});\n\n\u002F\u002F Account Linking\nawait auth.api.linkSocialAccount({\n  body: { provider: \"google\" },\n  headers: request.headers,\n});\n\nawait auth.api.unlinkAccount({\n  body: { providerId: \"google\", accountId: \"google_123\" },\n  headers: request.headers,\n});\n```\n\n#### Plugin API Methods\n\n**2FA Plugin**:\n```typescript\n\u002F\u002F Enable 2FA\nconst { totpUri, backupCodes } = await auth.api.enableTwoFactor({\n  body: { issuer: \"MyApp\" },\n  headers: request.headers,\n});\n\n\u002F\u002F Verify TOTP code\nawait auth.api.verifyTOTP({\n  body: { code: \"123456\", trustDevice: true },\n  headers: request.headers,\n});\n\n\u002F\u002F Generate backup codes\nconst { backupCodes } = await auth.api.generateBackupCodes({\n  headers: request.headers,\n});\n```\n\n**Organization Plugin**:\n```typescript\n\u002F\u002F Create organization\nconst org = await auth.api.createOrganization({\n  body: { name: \"Acme Corp\", slug: \"acme\" },\n  headers: request.headers,\n});\n\n\u002F\u002F Add member\nawait auth.api.addMember({\n  body: {\n    userId: \"user_123\",\n    role: \"admin\",\n    organizationId: org.id,\n  },\n  headers: request.headers,\n});\n\n\u002F\u002F Check permissions\nconst hasPermission = await auth.api.hasPermission({\n  body: {\n    organizationId: org.id,\n    permission: \"users:delete\",\n  },\n  headers: request.headers,\n});\n```\n\n**Admin Plugin**:\n```typescript\n\u002F\u002F List users with pagination\nconst users = await auth.api.listUsers({\n  query: {\n    search: \"john\",\n    limit: 10,\n    offset: 0,\n    sortBy: \"createdAt\",\n    sortOrder: \"desc\",\n  },\n  headers: request.headers,\n});\n\n\u002F\u002F Ban user\nawait auth.api.banUser({\n  body: {\n    userId: \"user_123\",\n    reason: \"Violation of ToS\",\n    expiresAt: new Date(\"2025-12-31\"),\n  },\n  headers: request.headers,\n});\n\n\u002F\u002F Impersonate user (for admin support)\nconst impersonationSession = await auth.api.impersonateUser({\n  body: {\n    userId: \"user_123\",\n    expiresIn: 3600, \u002F\u002F 1 hour\n  },\n  headers: request.headers,\n});\n```\n\n---\n\n### When to Use Which\n\n| Use Case | Use HTTP Endpoints | Use `auth.api.*` Methods |\n|----------|-------------------|--------------------------|\n| **Client-side auth** | ✅ Yes | ❌ No |\n| **Server middleware** | ❌ No | ✅ Yes |\n| **Background jobs** | ❌ No | ✅ Yes |\n| **Admin dashboards** | ✅ Yes (from client) | ✅ Yes (from server) |\n| **Custom auth flows** | ❌ No | ✅ Yes |\n| **Mobile apps** | ✅ Yes | ❌ No |\n| **API routes** | ✅ Yes (proxy to handler) | ✅ Yes (direct calls) |\n\n**Example: Protected Route Middleware**\n\n```typescript\nimport { Hono } from \"hono\";\nimport { createAuth } from \".\u002Fauth\";\nimport { createDatabase } from \".\u002Fdb\";\n\nconst app = new Hono\u003C{ Bindings: Env }>();\n\n\u002F\u002F Middleware using server-side API\napp.use(\"\u002Fapi\u002Fprotected\u002F*\", async (c, next) => {\n  const db = createDatabase(c.env.DB);\n  const auth = createAuth(db, c.env);\n\n  \u002F\u002F Use server-side method\n  const session = await auth.api.getSession({\n    headers: c.req.raw.headers,\n  });\n\n  if (!session) {\n    return c.json({ error: \"Unauthorized\" }, 401);\n  }\n\n  \u002F\u002F Attach to context\n  c.set(\"user\", session.user);\n  c.set(\"session\", session.session);\n\n  await next();\n});\n\n\u002F\u002F Protected route\napp.get(\"\u002Fapi\u002Fprotected\u002Fprofile\", async (c) => {\n  const user = c.get(\"user\");\n  return c.json({ user });\n});\n```\n\n---\n\n### Discovering Available Endpoints\n\nUse the **OpenAPI plugin** to see all endpoints in your configuration:\n\n```typescript\nimport { betterAuth } from \"better-auth\";\nimport { openAPI } from \"better-auth\u002Fplugins\";\n\nexport const auth = betterAuth({\n  database: \u002F* ... *\u002F,\n  plugins: [\n    openAPI(), \u002F\u002F Adds \u002Fapi\u002Fauth\u002Freference endpoint\n  ],\n});\n```\n\n**Interactive documentation**: Visit `http:\u002F\u002Flocalhost:8787\u002Fapi\u002Fauth\u002Freference`\n\nThis shows a **Scalar UI** with:\n- ✅ All available endpoints grouped by feature\n- ✅ Request\u002Fresponse schemas with types\n- ✅ Try-it-out functionality (test endpoints in browser)\n- ✅ Authentication requirements\n- ✅ Code examples in multiple languages\n\n**Programmatic access**:\n```typescript\nconst schema = await auth.api.generateOpenAPISchema();\nconsole.log(JSON.stringify(schema, null, 2));\n\u002F\u002F Returns full OpenAPI 3.0 spec\n```\n\n---\n\n### Quantified Time Savings\n\n**Building from scratch** (manual implementation):\n- Core auth endpoints (sign-up, sign-in, OAuth, sessions): **40 hours**\n- Email verification & password reset: **10 hours**\n- 2FA system (TOTP, backup codes, email OTP): **20 hours**\n- Organizations (teams, invitations, RBAC): **60 hours**\n- Admin panel (user management, impersonation): **30 hours**\n- Testing & debugging: **50 hours**\n- Security hardening: **20 hours**\n\n**Total manual effort**: **~220 hours** (5.5 weeks full-time)\n\n**With better-auth**:\n- Initial setup: **2-4 hours**\n- Customization & styling: **2-4 hours**\n\n**Total with better-auth**: **4-8 hours**\n\n**Savings**: **~97% development time**\n\n---\n\n### Key Takeaway\n\nbetter-auth provides **80+ production-ready endpoints** covering:\n- ✅ Core authentication (20 endpoints)\n- ✅ 2FA & passwordless (15 endpoints)\n- ✅ Organizations & teams (35 endpoints)\n- ✅ Admin & user management (15 endpoints)\n- ✅ Social OAuth (auto-configured callbacks)\n- ✅ OpenAPI documentation (interactive UI)\n\n**You write zero endpoint code.** Just configure features and call `auth.handler()`.\n\n---\n\n## Known Issues & Solutions\n\n### Issue 1: \"d1Adapter is not exported\" Error\n\n**Problem**: Code shows `import { d1Adapter } from 'better-auth\u002Fadapters\u002Fd1'` but this doesn't exist.\n\n**Symptoms**: TypeScript error or runtime error about missing export.\n\n**Solution**: Use Drizzle or Kysely instead:\n\n```typescript\n\u002F\u002F ❌ WRONG - This doesn't exist\nimport { d1Adapter } from 'better-auth\u002Fadapters\u002Fd1'\ndatabase: d1Adapter(env.DB)\n\n\u002F\u002F ✅ CORRECT - Use Drizzle\nimport { drizzleAdapter } from 'better-auth\u002Fadapters\u002Fdrizzle'\nimport { drizzle } from 'drizzle-orm\u002Fd1'\nconst db = drizzle(env.DB, { schema })\ndatabase: drizzleAdapter(db, { provider: \"sqlite\" })\n\n\u002F\u002F ✅ CORRECT - Use Kysely\nimport { Kysely } from 'kysely'\nimport { D1Dialect } from 'kysely-d1'\ndatabase: {\n  db: new Kysely({ dialect: new D1Dialect({ database: env.DB }) }),\n  type: \"sqlite\"\n}\n```\n\n**Source**: Verified from 4 production repositories using better-auth + D1\n\n---\n\n### Issue 2: Schema Generation Fails\n\n**Problem**: `npx better-auth migrate` doesn't create D1-compatible schema.\n\n**Symptoms**: Migration SQL has wrong syntax or doesn't work with D1.\n\n**Solution**: Use Drizzle Kit to generate migrations:\n\n```bash\n# Generate migration from Drizzle schema\nnpx drizzle-kit generate\n\n# Apply to D1\nwrangler d1 migrations apply my-app-db --remote\n```\n\n**Why**: Drizzle Kit generates SQLite-compatible SQL that works with D1.\n\n---\n\n### Issue 3: \"CamelCase\" vs \"snake_case\" Column Mismatch\n\n**Problem**: Database has `email_verified` but better-auth expects `emailVerified`.\n\n**Symptoms**: Session reads fail, user data missing fields.\n\n**⚠️ CRITICAL (v1.4.10+)**: Using Kysely's `CamelCasePlugin` **breaks join parsing** in better-auth adapter. The plugin converts join keys like `_joined_user_user_id` to `_joinedUserUserId`, causing user data to be null in session queries.\n\n**Solution for Drizzle**: Define schema with camelCase from the start (as shown in examples).\n\n**Solution for Kysely with CamelCasePlugin**: Use **separate Kysely instance** without CamelCasePlugin for better-auth:\n\n```typescript\n\u002F\u002F DB for better-auth (no CamelCasePlugin)\nconst authDb = new Kysely({\n  dialect: new D1Dialect({ database: env.DB }),\n})\n\n\u002F\u002F DB for app queries (with CamelCasePlugin)\nconst appDb = new Kysely({\n  dialect: new D1Dialect({ database: env.DB }),\n  plugins: [new CamelCasePlugin()],\n})\n\nexport const auth = betterAuth({\n  database: { db: authDb, type: \"sqlite\" },\n})\n```\n\n**Source**: [GitHub Issue #7136](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7136)\n\n---\n\n### Issue 4: D1 Eventual Consistency\n\n**Problem**: Session reads immediately after write return stale data.\n\n**Symptoms**: User logs in but `getSession()` returns null on next request.\n\n**Solution**: Use Cloudflare KV for session storage (strong consistency):\n\n```typescript\nimport { betterAuth } from \"better-auth\";\n\nexport function createAuth(db: Database, env: Env) {\n  return betterAuth({\n    database: drizzleAdapter(db, { provider: \"sqlite\" }),\n    session: {\n      storage: {\n        get: async (sessionId) => {\n          const session = await env.SESSIONS_KV.get(sessionId);\n          return session ? JSON.parse(session) : null;\n        },\n        set: async (sessionId, session, ttl) => {\n          await env.SESSIONS_KV.put(sessionId, JSON.stringify(session), {\n            expirationTtl: ttl,\n          });\n        },\n        delete: async (sessionId) => {\n          await env.SESSIONS_KV.delete(sessionId);\n        },\n      },\n    },\n  });\n}\n```\n\n**Add to `wrangler.toml`**:\n```toml\n[[kv_namespaces]]\nbinding = \"SESSIONS_KV\"\nid = \"your-kv-namespace-id\"\n```\n\n---\n\n### Issue 5: CORS Errors for SPA Applications\n\n**Problem**: CORS errors when auth API is on different origin than frontend.\n\n**Symptoms**: `Access-Control-Allow-Origin` errors in browser console.\n\n**Solution**: Configure CORS headers in Worker and ensure `trustedOrigins` match:\n\n```typescript\nimport { cors } from \"hono\u002Fcors\";\n\n\u002F\u002F CRITICAL: Both must match frontend origin exactly\napp.use(\n  \"\u002Fapi\u002Fauth\u002F*\",\n  cors({\n    origin: \"http:\u002F\u002Flocalhost:5173\", \u002F\u002F Frontend URL (no trailing slash)\n    credentials: true, \u002F\u002F Allow cookies\n    allowMethods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\"],\n  })\n);\n\n\u002F\u002F And in better-auth config\nexport const auth = betterAuth({\n  trustedOrigins: [\"http:\u002F\u002Flocalhost:5173\"], \u002F\u002F Same as CORS origin\n  \u002F\u002F ...\n});\n```\n\n**Common Mistakes**:\n- Typo in origin URL (trailing slash, http vs https, wrong port)\n- Mismatched origins between CORS config and `trustedOrigins`\n- CORS middleware registered AFTER auth routes (must be before)\n\n**Source**: [GitHub Issue #7434](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7434)\n\n---\n\n### Issue 6: OAuth Redirect URI Mismatch\n\n**Problem**: Social sign-in fails with \"redirect_uri_mismatch\" error.\n\n**Symptoms**: Google\u002FGitHub OAuth returns error after user consent.\n\n**Solution**: Ensure exact match in OAuth provider settings:\n\n```\nProvider setting: https:\u002F\u002Fyourdomain.com\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle\nbetter-auth URL:  https:\u002F\u002Fyourdomain.com\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle\n\n❌ Wrong: http vs https, trailing slash, subdomain mismatch\n✅ Right: Exact character-for-character match\n```\n\n**Check better-auth callback URL**:\n```typescript\n\u002F\u002F It's always: {baseURL}\u002Fapi\u002Fauth\u002Fcallback\u002F{provider}\nconst callbackURL = `${env.BETTER_AUTH_URL}\u002Fapi\u002Fauth\u002Fcallback\u002Fgoogle`;\nconsole.log(\"Configure this URL in Google Console:\", callbackURL);\n```\n\n---\n\n### Issue 7: Missing Dependencies\n\n**Problem**: TypeScript errors or runtime errors about missing packages.\n\n**Symptoms**: `Cannot find module 'drizzle-orm'` or similar.\n\n**Solution**: Install all required packages:\n\n**For Drizzle approach**:\n```bash\nnpm install better-auth drizzle-orm drizzle-kit @cloudflare\u002Fworkers-types\n```\n\n**For Kysely approach**:\n```bash\nnpm install better-auth kysely kysely-d1 @cloudflare\u002Fworkers-types\n```\n\n---\n\n### Issue 8: Email Verification Not Sending\n\n**Problem**: Email verification links never arrive.\n\n**Symptoms**: User signs up, but no email received.\n\n**Solution**: Implement `sendVerificationEmail` handler:\n\n```typescript\nexport const auth = betterAuth({\n  database: \u002F* ... *\u002F,\n  emailAndPassword: {\n    enabled: true,\n    requireEmailVerification: true,\n  },\n  emailVerification: {\n    sendVerificationEmail: async ({ user, url }) => {\n      \u002F\u002F Use your email service (SendGrid, Resend, etc.)\n      await sendEmail({\n        to: user.email,\n        subject: \"Verify your email\",\n        html: `\n          \u003Cp>Click the link below to verify your email:\u003C\u002Fp>\n          \u003Ca href=\"${url}\">Verify Email\u003C\u002Fa>\n        `,\n      });\n    },\n    sendOnSignUp: true,\n    autoSignInAfterVerification: true,\n    expiresIn: 3600, \u002F\u002F 1 hour\n  },\n});\n```\n\n**For Cloudflare**: Use Cloudflare Email Routing or external service (Resend, SendGrid).\n\n---\n\n### Issue 9: Session Expires Too Quickly\n\n**Problem**: Session expires unexpectedly or never expires.\n\n**Symptoms**: User logged out unexpectedly or session persists after logout.\n\n**Solution**: Configure session expiration:\n\n```typescript\nexport const auth = betterAuth({\n  database: \u002F* ... *\u002F,\n  session: {\n    expiresIn: 60 * 60 * 24 * 7, \u002F\u002F 7 days (in seconds)\n    updateAge: 60 * 60 * 24, \u002F\u002F Update session every 24 hours\n  },\n});\n```\n\n---\n\n### Issue 10: Social Provider Missing User Data\n\n**Problem**: Social sign-in succeeds but missing user data (name, avatar).\n\n**Symptoms**: `session.user.name` is null after Google\u002FGitHub sign-in.\n\n**Solution**: Request additional scopes:\n\n```typescript\nsocialProviders: {\n  google: {\n    clientId: env.GOOGLE_CLIENT_ID,\n    clientSecret: env.GOOGLE_CLIENT_SECRET,\n    scope: [\"openid\", \"email\", \"profile\"], \u002F\u002F Include 'profile' for name\u002Fimage\n  },\n  github: {\n    clientId: env.GITHUB_CLIENT_ID,\n    clientSecret: env.GITHUB_CLIENT_SECRET,\n    scope: [\"user:email\", \"read:user\"], \u002F\u002F 'read:user' for full profile\n  },\n}\n```\n\n---\n\n### Issue 11: TypeScript Errors with Drizzle Schema\n\n**Problem**: TypeScript complains about schema types.\n\n**Symptoms**: `Type 'DrizzleD1Database' is not assignable to...`\n\n**Solution**: Export proper types from database:\n\n```typescript\n\u002F\u002F src\u002Fdb\u002Findex.ts\nimport { drizzle, type DrizzleD1Database } from \"drizzle-orm\u002Fd1\";\nimport * as schema from \".\u002Fschema\";\n\nexport type Database = DrizzleD1Database\u003Ctypeof schema>;\n\nexport function createDatabase(d1: D1Database): Database {\n  return drizzle(d1, { schema });\n}\n```\n\n---\n\n### Issue 12: Wrangler Dev Mode Not Working\n\n**Problem**: `wrangler dev` fails with database errors.\n\n**Symptoms**: \"Database not found\" or migration errors in local dev.\n\n**Solution**: Apply migrations locally first:\n\n```bash\n# Apply migrations to local D1\nwrangler d1 migrations apply my-app-db --local\n\n# Then run dev server\nwrangler dev\n```\n\n---\n\n### Issue 13: User Data Updates Not Reflecting in UI (with TanStack Query)\n\n**Problem**: After updating user data (e.g., avatar, name), changes don't appear in `useSession()` despite calling `queryClient.invalidateQueries()`.\n\n**Symptoms**: Avatar image or user profile data appears stale after successful update. TanStack Query cache shows updated data, but better-auth session still shows old values.\n\n**Root Cause**: better-auth uses **nanostores** for session state management, not TanStack Query. Calling `queryClient.invalidateQueries()` only invalidates React Query cache, not the better-auth nanostore.\n\n**Solution**: Manually notify the nanostore after updating user data:\n\n```typescript\n\u002F\u002F Update user data\nconst { data, error } = await authClient.updateUser({\n  image: newAvatarUrl,\n  name: newName\n})\n\nif (!error) {\n  \u002F\u002F Manually invalidate better-auth session state\n  authClient.$store.notify('$sessionSignal')\n\n  \u002F\u002F Optional: Also invalidate React Query if using it for other data\n  queryClient.invalidateQueries({ queryKey: ['user-profile'] })\n}\n```\n\n**When to use**:\n- Using better-auth + TanStack Query together\n- Updating user profile fields (name, image, email)\n- Any operation that modifies session user data client-side\n\n**Alternative**: Call `refetch()` from `useSession()`, but `$store.notify()` is more direct:\n\n```typescript\nconst { data: session, refetch } = authClient.useSession()\n\u002F\u002F After update\nawait refetch()\n```\n\n**Note**: `$store` is an undocumented internal API. This pattern is production-validated but may change in future better-auth versions.\n\n**Source**: Community-discovered pattern, production use verified\n\n---\n\n### Issue 14: apiKey Table Schema Mismatch with D1\n\n**Problem**: better-auth CLI (`npx @better-auth\u002Fcli generate`) fails with \"Failed to initialize database adapter\" when using D1.\n\n**Symptoms**: CLI cannot connect to D1 to introspect schema. Running migrations through CLI doesn't work.\n\n**Root Cause**: The CLI expects a direct SQLite connection, but D1 requires Cloudflare's binding API.\n\n**Solution**: Skip the CLI and create migrations manually using the documented apiKey schema:\n\n```sql\nCREATE TABLE api_key (\n  id TEXT PRIMARY KEY NOT NULL,\n  user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,\n  name TEXT,\n  start TEXT,\n  prefix TEXT,\n  key TEXT NOT NULL,\n  enabled INTEGER DEFAULT 1,\n  rate_limit_enabled INTEGER,\n  rate_limit_time_window INTEGER,\n  rate_limit_max INTEGER,\n  request_count INTEGER DEFAULT 0,\n  last_request INTEGER,\n  remaining INTEGER,\n  refill_interval INTEGER,\n  refill_amount INTEGER,\n  last_refill_at INTEGER,\n  expires_at INTEGER,\n  permissions TEXT,\n  metadata TEXT,\n  created_at INTEGER NOT NULL,\n  updated_at INTEGER NOT NULL\n);\n```\n\n**Key Points**:\n- The table has exactly **21 columns** (as of better-auth v1.4+)\n- Column names use `snake_case` (e.g., `rate_limit_time_window`, not `rateLimitTimeWindow`)\n- D1 doesn't support `ALTER TABLE DROP COLUMN` - if schema drifts, use fresh migration pattern (drop and recreate tables)\n- In Drizzle adapter config, use `apikey` (lowercase) as the table name mapping\n\n**Fresh Migration Pattern for D1**:\n```sql\n-- Drop in reverse dependency order\nDROP TABLE IF EXISTS api_key;\nDROP TABLE IF EXISTS session;\n-- ... other tables\n\n-- Recreate with clean schema\nCREATE TABLE api_key (...);\n```\n\n**Source**: Production debugging with D1 + better-auth apiKey plugin\n\n---\n\n### Issue 15: Admin Plugin Requires DB Role (Dual-Auth)\n\n**Problem**: Admin plugin methods like `listUsers` fail with \"You are not allowed to list users\" even though your middleware passes.\n\n**Symptoms**: Custom `requireAdmin` middleware (checking ADMIN_EMAILS env var) passes, but `auth.api.listUsers()` returns 403.\n\n**Root Cause**: better-auth admin plugin has **two** authorization layers:\n1. **Your middleware** - Custom check (e.g., ADMIN_EMAILS)\n2. **better-auth internal** - Checks `user.role === 'admin'` in database\n\nBoth must pass for admin plugin methods to work.\n\n**Solution**: Set user role to 'admin' in the database:\n\n```sql\n-- Fix for existing users\nUPDATE user SET role = 'admin' WHERE email = 'admin@example.com';\n```\n\nOr use the admin UI\u002FAPI to set roles after initial setup.\n\n**Why**: The admin plugin's `listUsers`, `banUser`, `impersonateUser`, etc. all check `user.role` in the database, not your custom middleware logic.\n\n**Source**: Production debugging - misleading error message led to root cause discovery via `wrangler tail`\n\n---\n\n### Issue 16: Organization\u002FTeam updated_at Must Be Nullable\n\n**Problem**: Organization creation fails with SQL constraint error even though API returns \"slug already exists\".\n\n**Symptoms**:\n- Error message says \"An organization with this slug already exists\"\n- Database table is actually empty\n- `wrangler tail` shows: `Failed query: insert into \"organization\" ... values (?, ?, ?, null, null, ?, null)`\n\n**Root Cause**: better-auth inserts `null` for `updated_at` on creation (only sets it on updates). If your schema has `NOT NULL` constraint, insert fails.\n\n**Solution**: Make `updated_at` nullable in both schema and migrations:\n\n```typescript\n\u002F\u002F Drizzle schema - CORRECT\nexport const organization = sqliteTable('organization', {\n  \u002F\u002F ...\n  updatedAt: integer('updated_at', { mode: 'timestamp' }), \u002F\u002F No .notNull()\n});\n\nexport const team = sqliteTable('team', {\n  \u002F\u002F ...\n  updatedAt: integer('updated_at', { mode: 'timestamp' }), \u002F\u002F No .notNull()\n});\n```\n\n```sql\n-- Migration - CORRECT\nCREATE TABLE organization (\n  -- ...\n  updated_at INTEGER  -- No NOT NULL\n);\n```\n\n**Applies to**: `organization` and `team` tables (possibly other plugin tables)\n\n**Source**: Production debugging - `wrangler tail` revealed actual SQL error behind misleading \"slug exists\" message\n\n---\n\n### Issue 17: API Response Double-Nesting (listMembers, etc.)\n\n**Problem**: Custom API endpoints return double-nested data like `{ members: { members: [...], total: N } }`.\n\n**Symptoms**: UI shows \"undefined\" for counts, empty lists despite data existing.\n\n**Root Cause**: better-auth methods like `listMembers` return `{ members: [...], total: N }`. Wrapping with `c.json({ members: result })` creates double nesting.\n\n**Solution**: Extract the array from better-auth response:\n\n```typescript\n\u002F\u002F ❌ WRONG - Double nesting\nconst result = await auth.api.listMembers({ ... });\nreturn c.json({ members: result });\n\u002F\u002F Returns: { members: { members: [...], total: N } }\n\n\u002F\u002F ✅ CORRECT - Extract array\nconst result = await auth.api.listMembers({ ... });\nconst members = result?.members || [];\nreturn c.json({ members });\n\u002F\u002F Returns: { members: [...] }\n```\n\n**Affected methods** (return objects, not arrays):\n- `listMembers` → `{ members: [...], total: N }`\n- `listUsers` → `{ users: [...], total: N, limit: N }`\n- `listOrganizations` → `{ organizations: [...] }` (check structure)\n- `listInvitations` → `{ invitations: [...] }`\n\n**Pattern**: Always check better-auth method return types before wrapping in your API response.\n\n**Source**: Production debugging - UI showed \"undefined\" count, API inspection revealed nesting issue\n\n---\n\n### Issue 18: Expo Client fromJSONSchema Crash (v1.4.16)\n\n**Problem**: Importing `expoClient` from `@better-auth\u002Fexpo\u002Fclient` crashes with `TypeError: Cannot read property 'fromJSONSchema' of undefined` on v1.4.16.\n\n**Symptoms**: Runtime crash immediately when importing expoClient in React Native\u002FExpo apps.\n\n**Root Cause**: Regression introduced after PR #6933 (cookie-based OAuth state fix for Expo). One of 3 commits after f4a9f15 broke the build.\n\n**Solution**:\n- **Temporary**: Use continuous build at commit `f4a9f15` (pre-regression)\n- **Permanent**: Wait for fix (issue #7491 open as of 2026-01-20)\n\n```typescript\n\u002F\u002F Crashes on v1.4.16\nimport { expoClient } from '@better-auth\u002Fexpo\u002Fclient'\n\n\u002F\u002F Workaround: Use continuous build at f4a9f15\n\u002F\u002F Or wait for fix in next release\n```\n\n**Source**: [GitHub Issue #7491](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7491)\n\n---\n\n### Issue 19: additionalFields string[] Returns Stringified JSON\n\n**Problem**: After v1.4.12, `additionalFields` with `type: 'string[]'` return stringified arrays (`'[\"a\",\"b\"]'`) instead of native arrays when querying via Drizzle directly.\n\n**Symptoms**: `user.notificationTokens` is a string, not an array. Code expecting arrays breaks.\n\n**Root Cause**: In Drizzle adapter, `string[]` fields are stored with `mode: 'json'`, which expects arrays. But better-auth v1.4.4+ passes strings to Drizzle, causing double-stringification. When querying **directly via Drizzle**, the value is a string, but when using **better-auth `internalAdapter`**, a transformer correctly returns an array.\n\n**Solution**:\n1. **Use better-auth `internalAdapter`** instead of querying Drizzle directly (has transformer)\n2. **Change Drizzle schema** to `.jsonb()` for string[] fields\n3. **Manually parse** JSON strings until fixed\n\n```typescript\n\u002F\u002F Config\nadditionalFields: {\n  notificationTokens: {\n    type: 'string[]',\n    required: true,\n    input: true,\n  },\n}\n\n\u002F\u002F Create user\nnotificationTokens: ['token1', 'token2']\n\n\u002F\u002F Result in DB (when querying via Drizzle directly)\n\u002F\u002F '[\"token1\",\"token2\"]' (string, not array)\n```\n\n**Source**: [GitHub Issue #7440](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7440)\n\n---\n\n### Issue 20: additionalFields \"returned\" Property Blocks Input\n\n**Problem**: Setting `returned: false` on `additionalFields` prevents field from being saved via API, even with `input: true`.\n\n**Symptoms**: Field never saved to database when creating\u002Fupdating via API endpoints.\n\n**Root Cause**: The `returned: false` property blocks both read AND write operations, not just reads as intended. The `input: true` property should control write access independently.\n\n**Solution**:\n- Don't use `returned: false` if you need API write access\n- Write via server-side methods (`auth.api.*`) instead\n\n```typescript\n\u002F\u002F Organization plugin config\nadditionalFields: {\n  secretField: {\n    type: 'string',\n    required: true,\n    input: true,      \u002F\u002F Should allow API writes\n    returned: false,  \u002F\u002F Should only block reads, but blocks writes too\n  },\n}\n\n\u002F\u002F API request to create organization\n\u002F\u002F secretField is never saved to database\n```\n\n**Source**: [GitHub Issue #7489](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7489)\n\n---\n\n### Issue 21: freshAge Based on Creation Time, Not Activity\n\n**Problem**: `session.freshAge` checks time-since-creation, NOT recent activity. Active sessions become \"not fresh\" after `freshAge` elapses, even if used constantly.\n\n**Symptoms**: \"Fresh session required\" endpoints reject valid active sessions.\n\n**Why It Happens**: The `freshSessionMiddleware` checks `Date.now() - (session.updatedAt || session.createdAt)`, but `updatedAt` only changes when the session is refreshed based on `updateAge`. If `updateAge > freshAge`, the session becomes \"not fresh\" before `updatedAt` is bumped.\n\n**Solution**:\n1. **Set `updateAge \u003C= freshAge`** to ensure freshness is updated before expiry\n2. **Avoid \"fresh session required\"** gating for long-lived sessions\n3. **Accept as design**: freshAge is strictly time-since-creation (maintainer confirmed)\n\n```typescript\n\u002F\u002F Config\nsession: {\n  expiresIn: 60 * 60 * 24 * 7,    \u002F\u002F 7 days\n  freshAge: 60 * 60 * 24,          \u002F\u002F 24 hours\n  updateAge: 60 * 60 * 24 * 3,     \u002F\u002F 3 days (> freshAge!) ⚠️ PROBLEM\n\n  \u002F\u002F CORRECT - updateAge \u003C= freshAge\n  updateAge: 60 * 60 * 12,         \u002F\u002F 12 hours (\u003C freshAge)\n}\n\n\u002F\u002F Timeline with bad config:\n\u002F\u002F T+0h: User signs in (createdAt = now)\n\u002F\u002F T+12h: User makes requests (session active, still fresh)\n\u002F\u002F T+25h: User makes request (session active, BUT NOT FRESH - freshAge elapsed)\n\u002F\u002F Result: \"Fresh session required\" endpoints reject active session\n```\n\n**Source**: [GitHub Issue #7472](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7472)\n\n---\n\n### Issue 22: OAuth Token Endpoints Return Wrapped JSON\n\n**Problem**: OAuth 2.1 and OIDC token endpoints return `{ \"response\": { ...tokens... } }` instead of spec-compliant top-level JSON. OAuth clients expect `{ \"access_token\": \"...\", \"token_type\": \"bearer\" }` at root.\n\n**Symptoms**: OAuth clients fail with `Bearer undefined` or `invalid_token`.\n\n**Root Cause**: The endpoint pipeline returns `{ response, headers, status }` for internal use, which gets serialized directly for HTTP requests. This breaks OAuth\u002FOIDC spec requirements.\n\n**Solution**:\n- **Temporary**: Manually unwrap `.response` field on client\n- **Permanent**: Wait for fix (issue #7355 open, accepting contributions)\n\n```typescript\n\u002F\u002F Expected (spec-compliant)\n{ \"access_token\": \"...\", \"token_type\": \"bearer\", \"expires_in\": 3600 }\n\n\u002F\u002F Actual (wrapped)\n{ \"response\": { \"access_token\": \"...\", \"token_type\": \"bearer\", \"expires_in\": 3600 } }\n\n\u002F\u002F Result: OAuth clients fail to parse, send `Bearer undefined`\n```\n\n**Source**: [GitHub Issue #7355](https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Fissues\u002F7355)\n\n---\n\n## Migration Guides\n\n### From Clerk\n\n**Key differences**:\n- Clerk: Third-party service → better-auth: Self-hosted\n- Clerk: Proprietary → better-auth: Open source\n- Clerk: Monthly cost → better-auth: Free\n\n**Migration steps**:\n\n1. **Export user data** from Clerk (CSV or API)\n2. **Import into better-auth database**:\n   ```typescript\n   \u002F\u002F migration script\n   const clerkUsers = await fetchClerkUsers();\n\n   for (const clerkUser of clerkUsers) {\n     await db.insert(user).values({\n       id: clerkUser.id,\n       email: clerkUser.email,\n       emailVerified: clerkUser.email_verified,\n       name: clerkUser.first_name + \" \" + clerkUser.last_name,\n       image: clerkUser.profile_image_url,\n     });\n   }\n   ```\n3. **Replace Clerk SDK** with better-auth client:\n   ```typescript\n   \u002F\u002F Before (Clerk)\n   import { useUser } from \"@clerk\u002Fnextjs\";\n   const { user } = useUser();\n\n   \u002F\u002F After (better-auth)\n   import { authClient } from \"@\u002Flib\u002Fauth-client\";\n   const { data: session } = authClient.useSession();\n   const user = session?.user;\n   ```\n4. **Update middleware** for session verification\n5. **Configure social providers** (same OAuth apps, different config)\n\n---\n\n### From Auth.js (NextAuth)\n\n**Key differences**:\n- Auth.js: Limited features → better-auth: Comprehensive (2FA, orgs, etc.)\n- Auth.js: Callbacks-heavy → better-auth: Plugin-based\n- Auth.js: Session handling varies → better-auth: Consistent\n\n**Migration steps**:\n\n1. **Database schema**: Auth.js and better-auth use similar schemas, but column names differ\n2. **Replace configuration**:\n   ```typescript\n   \u002F\u002F Before (Auth.js)\n   import NextAuth from \"next-auth\";\n   import GoogleProvider from \"next-auth\u002Fproviders\u002Fgoogle\";\n\n   export default NextAuth({\n     providers: [GoogleProvider({ \u002F* ... *\u002F })],\n   });\n\n   \u002F\u002F After (better-auth)\n   import { betterAuth } from \"better-auth\";\n\n   export const auth = betterAuth({\n     socialProviders: {\n       google: { \u002F* ... *\u002F },\n     },\n   });\n   ```\n3. **Update client hooks**:\n   ```typescript\n   \u002F\u002F Before\n   import { useSession } from \"next-auth\u002Freact\";\n\n   \u002F\u002F After\n   import { authClient } from \"@\u002Flib\u002Fauth-client\";\n   const { data: session } = authClient.useSession();\n   ```\n\n---\n\n## Additional Resources\n\n### Official Documentation\n\n- **Homepage**: https:\u002F\u002Fbetter-auth.com\n- **Introduction**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintroduction\n- **Installation**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Finstallation\n- **Basic Usage**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fbasic-usage\n\n### Core Concepts\n\n- **Session Management**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fsession-management\n- **Users & Accounts**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fusers-accounts\n- **Client SDK**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fclient\n- **Plugins System**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Fplugins\n\n### Authentication Methods\n\n- **Email & Password**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fauthentication\u002Femail-password\n- **OAuth Providers**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fconcepts\u002Foauth\n\n### Plugin Documentation\n\n**Core Plugins**:\n- **2FA (Two-Factor)**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002F2fa\n- **Organization**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Forganization\n- **Admin**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fadmin\n- **Multi-Session**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmulti-session\n- **API Key**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fapi-key\n- **Generic OAuth**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fgeneric-oauth\n\n**Passwordless Plugins**:\n- **Passkey**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fpasskey\n- **Magic Link**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmagic-link\n- **Email OTP**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Femail-otp\n- **Phone Number**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fphone-number\n- **Anonymous**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fanonymous\n\n**Advanced Plugins**:\n- **Username**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fusername\n- **JWT**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fjwt\n- **OpenAPI**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fopen-api\n- **OIDC Provider**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Foidc-provider\n- **SSO**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fsso\n- **Stripe**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fstripe\n- **MCP**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fplugins\u002Fmcp\n\n### Framework Integrations\n\n- **TanStack Start**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Ftanstack\n- **Expo (React Native)**: https:\u002F\u002Fwww.better-auth.com\u002Fdocs\u002Fintegrations\u002Fexpo\n\n### Community & Support\n\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth (22.4k ⭐)\n- **Examples**: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Ftree\u002Fmain\u002Fexamples\n- **Discord**: https:\u002F\u002Fdiscord.gg\u002Fbetter-auth\n- **Changelog**: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Freleases\n\n### Related Documentation\n\n- **Drizzle ORM**: https:\u002F\u002Form.drizzle.team\u002Fdocs\u002Fget-started-sqlite\n- **Kysely**: https:\u002F\u002Fkysely.dev\u002F\n\n---\n\n## Production Examples\n\n**Verified working D1 repositories** (all use Drizzle or Kysely):\n\n1. **zpg6\u002Fbetter-auth-cloudflare** - Drizzle + D1 (includes CLI)\n2. **zwily\u002Fexample-react-router-cloudflare-d1-drizzle-better-auth** - Drizzle + D1\n3. **foxlau\u002Freact-router-v7-better-auth** - Drizzle + D1\n4. **matthewlynch\u002Fbetter-auth-react-router-cloudflare-d1** - Kysely + D1\n\n**None** use a direct `d1Adapter` - all require Drizzle\u002FKysely.\n\n---\n\n## Version Compatibility\n\n**Tested with**:\n- `better-auth@1.4.10`\n- `drizzle-orm@0.45.1`\n- `drizzle-kit@0.31.8`\n- `kysely@0.28.9`\n- `kysely-d1@0.4.0`\n- `@cloudflare\u002Fworkers-types@latest`\n- `hono@4.11.3`\n- Node.js 18+, Bun 1.0+\n\n**Breaking changes**:\n- v1.4.6: `allowImpersonatingAdmins` defaults to `false`\n- v1.4.0: ESM-only (no CommonJS)\n- v1.3.0: Multi-team table structure change\n\nCheck changelog: https:\u002F\u002Fgithub.com\u002Fbetter-auth\u002Fbetter-auth\u002Freleases\n\n---\n\n## Community Resources\n\n**Cloudflare-specific guides:**\n- [zpg6\u002Fbetter-auth-cloudflare](https:\u002F\u002Fgithub.com\u002Fzpg6\u002Fbetter-auth-cloudflare) - Drizzle + D1 reference\n- [Hono + better-auth on Cloudflare](https:\u002F\u002Fhono.dev\u002Fexamples\u002Fbetter-auth-on-cloudflare) - Official Hono example\n- [React Router + Cloudflare D1](https:\u002F\u002Fdev.to\u002Fatman33\u002Fsetup-better-auth-with-react-router-cloudflare-d1-2ad4) - React Router v7 guide\n- [SvelteKit + Cloudflare D1](https:\u002F\u002Fmedium.com\u002F@dasfacc\u002Fsveltekit-better-auth-using-cloudflare-d1-and-drizzle-91d9d9a6d0b4) - SvelteKit guide\n\n---\n\n**Token Efficiency**:\n- **Without skill**: ~35,000 tokens (D1 adapter errors, 15+ plugins, rate limiting, session caching, database hooks, mobile integration)\n- **With skill**: ~8,000 tokens (focused on errors + patterns + all plugins + API reference)\n- **Savings**: ~77% (~27,000 tokens)\n\n**Errors prevented**: 22 documented issues with exact solutions\n**Key value**: D1 adapter requirement, nodejs_compat flag, OAuth 2.1 Provider, Bearer\u002FOneTap\u002FSCIM\u002FAnonymous plugins, rate limiting, session caching, database hooks, Expo integration, 80+ endpoint reference, additionalFields bugs, freshAge behavior, OAuth token wrapping\n\n---\n\n**Last verified**: 2026-01-21 | **Skill version**: 5.1.0 | **Changes**: Added 5 new issues from post-training-cutoff research (Expo fromJSONSchema crash, additionalFields string[] bug, additionalFields returned property bug, freshAge not activity-based, OAuth token wrapping). Expanded Issue #3 with Kysely CamelCasePlugin join parsing failure. Expanded Issue #5 with Hono CORS pattern. Added Cloudflare Workers DB binding constraints note. Added TanStack Start session nullability pattern. Updated to v1.4.16.\n",{"name":5,"description":43,"allowed-tools":44,"user-invocable":51},"Self-hosted auth for TypeScript\u002FCloudflare Workers with social auth, 2FA, passkeys, organizations, RBAC, and 15+ plugins. Requires Drizzle ORM or Kysely for D1 (no direct adapter). Self-hosted alternative to Clerk\u002FAuth.js.\n\nUse when: self-hosting auth on D1, building OAuth provider, multi-tenant SaaS, or troubleshooting D1 adapter errors, session caching, rate limits, Expo crashes, additionalFields bugs.\n",[45,46,47,48,49,50],"Read","Write","Edit","Bash","Glob","Grep",true,"main","f4cb2d49f7667e79ef7804f50396d5aaffdf1f56","安全与密码\u002Fbetter-auth",1,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification","https:\u002F\u002Fgithub.com\u002FKernel8901","a little little little dobe in life but science geek","2026-04-05 16:43:56",{"source":8,"skillName":5,"commands":61,"prompt":71,"zipAvailable":51},[62,65,68],{"tool":63,"command":64},"npx","npx skills add Kernel8901\u002Fai-agent-skills-classification --skill better-auth",{"tool":66,"command":67},"bunx","bunx skills add Kernel8901\u002Fai-agent-skills-classification --skill better-auth",{"tool":69,"command":70},"pnpm","pnpm dlx skills add Kernel8901\u002Fai-agent-skills-classification --skill better-auth","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002FSKILL.md",[73,79,83,89,93,97,103,107,111,115,119,123,127,131],{"path":74,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":77,"sourceHtmlUrl":78},"_meta.json","REFERENCE","参考文档",286,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002F_meta.json",{"path":80,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":81,"sourceHtmlUrl":82},".claude-plugin\u002Fplugin.json",670,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002F.claude-plugin\u002Fplugin.json",{"path":84,"resourceType":85,"resourceTypeDesc":86,"sizeBytes":87,"sourceHtmlUrl":88},"assets\u002Fauth-flow-diagram.md","ASSET","资产文件",24607,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Fassets\u002Fauth-flow-diagram.md",{"path":90,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":91,"sourceHtmlUrl":92},"commands\u002Fsetup.md",6041,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Fcommands\u002Fsetup.md",{"path":94,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":95,"sourceHtmlUrl":96},"README.md",10074,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002FREADME.md",{"path":98,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Fcloudflare-worker-drizzle.ts","SCRIPT","脚本",12791,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Freferences\u002Fcloudflare-worker-drizzle.ts",{"path":104,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":105,"sourceHtmlUrl":106},"references\u002Fcloudflare-worker-kysely.ts",9700,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Freferences\u002Fcloudflare-worker-kysely.ts",{"path":108,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":109,"sourceHtmlUrl":110},"references\u002Fdatabase-schema.ts",11109,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Freferences\u002Fdatabase-schema.ts",{"path":112,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":113,"sourceHtmlUrl":114},"references\u002Fhono-cloudflare.ts",6384,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Freferences\u002Fhono-cloudflare.ts",{"path":116,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":117,"sourceHtmlUrl":118},"references\u002Fnextjs\u002Fpostgres-example.ts",4122,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Freferences\u002Fnextjs\u002Fpostgres-example.ts",{"path":120,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":121,"sourceHtmlUrl":122},"references\u002Fnextjs\u002FREADME.md",1142,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Freferences\u002Fnextjs\u002FREADME.md",{"path":124,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":125,"sourceHtmlUrl":126},"references\u002Freact-client-hooks.tsx",13105,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Freferences\u002Freact-client-hooks.tsx",{"path":128,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":129,"sourceHtmlUrl":130},"rules\u002Fbetter-auth.md",2924,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Frules\u002Fbetter-auth.md",{"path":132,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":133,"sourceHtmlUrl":134},"scripts\u002Fsetup-d1-drizzle.sh",10042,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F安全与密码\u002Fbetter-auth\u002Fscripts\u002Fsetup-d1-drizzle.sh",[136,160,183,191,198,224],{"skillNo":137,"name":138,"nameZh":6,"description":139,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":140,"categories":141,"keywords":142,"publishedAt":38},"01M6Q5R6WZ06RRB9RQTW54B34B","zyfai","Earn yield on any Ethereum wallet on Base, Arbitrum, and Plasma. Use when a user wants passive DeFi yield on their funds. Deploys a non-custodial subaccount (Safe) linked to their EOA, enables automated yield optimization, and lets them deposit\u002Fwithdraw anytime.","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzyfai-sdk\u002FSKILL.md",[],[138,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159],"safe","ethereum","defi","Optimization","user","use","Wallet","base","deposit","withdraw","yield","arbitrum","non-custodial","passive","defi yield","earn","yield optimization",{"skillNo":161,"name":162,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":163,"categories":164,"keywords":165,"publishedAt":38},"01M6Q5R337B5JSNER4P4YS03TN","zerion-api","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzerion-api\u002FSKILL.md",[],[166,167,168,169,170,171,172,145,173,149,174,175,176,177,178,179,180,181,182],"api","zerion api","zerion","MCP","mcp server","server","blockchain","transactions","crypto wallet","crypto","evm","solana","query","across","positions","token","prices",{"skillNo":184,"name":185,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":186,"categories":187,"keywords":188,"publishedAt":38},"01M6Q5QZFYTDAZMZ27BN5VZXAR","zerion-api-skill","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzerion-api-skill\u002FSKILL.md",[],[166,189,190,167,168,169,170,171,172,145,173,149,175,176,177,178,179,180,181,182],"api skill","zerion api skill",{"skillNo":192,"name":193,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":194,"categories":195,"keywords":196,"publishedAt":38},"01M6Q5QW17QW98RA3FE45E4RD8","zerion-api-mcp","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzerion-api-mcp\u002FSKILL.md",[],[169,166,197,167,168,170,171,145,173,149,174,175,176,177,178,179,180,181,182],"zerion api mcp",{"skillNo":199,"name":200,"nameZh":6,"description":201,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":202,"categories":203,"keywords":204,"publishedAt":38},"01M6Q5QQYZB7A501BDEQWKGSJT","yahoo-finance-forex","Fetches real-time FOREX news and market data from Yahoo Finance for major currency pairs (EUR\u002FUSD, GBP\u002FUSD, USD\u002FJPY, etc.). Analyzes sentiment and provides trading context.","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fyahoo-finance-forex\u002FSKILL.md",[],[205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,26],"finance","yahoo finance","forex","yahoo","yahoo finance forex","github","https","sentiment","real-time","python3","install","Market","usd","news","time","currency","gbp","pip","market data",{"skillNo":225,"name":226,"nameZh":6,"description":227,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":228,"categories":229,"keywords":230,"publishedAt":38},"01M6Q5QM6VS84WZVM7BKXXPF32","yahoo-finance","This skill should be used when the user asks to \"get stock prices\", \"check stock quotes\", \"look up earnings\", \"get financial data\", \"find trending stocks\", or needs stock market data from Yahoo Finance.","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fyahoo-finance-cli\u002FSKILL.md",[],[205,206,208,231,232,233,234,235,236,216,237,238,239,240,241,242,243,244,182,223],"cli","homebrew","find","check","brew","up","local","get","stock","link","trending","sf","quotes","ln"]