NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm, #4985 most downloaded on npm
The most comprehensive authentication framework for TypeScript.
Latest stable
1.7.20
Last release 12 days ago
10 Nov 2026
Ships fairly regularly
a new release about every 1 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
3 years old
957 releases · first in 2024
Drag across the ruler to compare, or tap a release to open it.
Fixed rate limits to be enforced before plugin request handlers run
better-authdeviceAuthorization() throwing a ZodError when called without a schema option under Zod v4 (#9939)input: false (#10196)TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE (#10210)displayUsername fallbacks that pass username validation during email sign-up (#10182)For detailed changes, see CHANGELOG
@better-auth/ssojavascript: or data: (#10225)For detailed changes, see CHANGELOG
@better-auth/api-keyX-Forwarded-For spoofing in multi-hop proxy chains (#10203)For detailed changes, see CHANGELOG
authdisableMigration: true to be respected on plugin schema tables during generation and runtime migration (#10198)BETTER_AUTH_SECRET values with 32 characters instead of 16 (#10186)For detailed changes, see CHANGELOG
@better-auth/kysely-adapteradapter.update to return null when no matching row is found (#10180)For detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@Bekacru, @benpsnyder, @bytaesu, @gustavovalverde, @moonevm, @Paola3stefania, @ping-maxwell, @rachit367
Full changelog: v1.6.20...v1.6.21
Your coding agent can read these notes before it upgrades. Set up the MCP server →
#10212 e0762a1 Thanks @bytaesu! - In root-mounted deployments, requests whose path does not start with the configured basePath now return 404 instead of resolving to an endpoint.
#10187 882cf9e Thanks @ping-maxwell! - Admin permission changes and bans now take effect immediately for admin APIs, even when session cookie cache is enabled. Sensitive session checks also continue to work in stateless apps where signed cookies are the session record.
#9939 f52e1ab Thanks @benpsnyder! - fixes a bug causing deviceAuthorization() throwing a ZodError at construction when called without a schema option
#10196 b5bec19 Thanks @Paola3stefania! - OAuth sign-up and account-link profile sync now ignore provider profile values for user fields marked input: false. Input-allowed additional fields still persist from mapProfileToUser, and schema defaults still apply when OAuth creates a user. Apps that used mapProfileToUser to fill input: false fields should set those fields in server-side provisioning code instead.
#10197 816d7f9 Thanks @Paola3stefania! - Google sign-in now accepts hd: "*" to allow any Google Workspace hosted domain while still rejecting tokens with no hosted-domain claim.
Google One Tap now applies the configured Google hosted-domain restriction before creating a session.
#10192 239bcc8 Thanks @bytaesu! - Validate PayPal user info against the verified ID token subject during social sign-in.
#10228 1bc370a Thanks @gustavovalverde! - The SIWE plugin no longer binds a provided email that already belongs to another account. With anonymous set to false, /siwe/verify previously created the new account using that email even when it was already in use; it now keeps the wallet-derived address in that case, so one email cannot be attached to two accounts.
#10198 570267c Thanks @rachit367! - Honor disableMigration on plugin schema tables. Tables flagged with disableMigration: true are now skipped by better-auth generate (Drizzle and Prisma output) and by the runtime migrator, instead of being emitted and created anyway. The flag was previously dropped while assembling the table list, so it had no effect.
#10182 461ca6f Thanks @bytaesu! - Only store display username fallbacks as usernames when they pass username validation during email sign-up.
#10183 88409b0 Thanks @bytaesu! - Require OAuth proxy profile callbacks to match an issued OAuth state before creating sessions.
#10203 5953157 Thanks @bytaesu! - Rate limiting no longer trusts multi-hop X-Forwarded-For chains, preventing a client behind an appending proxy from spoofing the leftmost hop to bypass the per-IP rate limit. Single-value IP headers continue to work. To key the real client behind a proxy chain, set advanced.ipAddress.trustedProxies to your reverse-proxy IPs or CIDR ranges (the chain is walked right to left, skipping trusted hops), or point advanced.ipAddress.ipAddressHeaders at a single trusted client-IP header.
#10191 b046f9e Thanks @bytaesu! - Rate limit client requests before plugin request handlers run.
#10210 ae647b4 Thanks @gustavovalverde! - Two-factor verification now locks out after five wrong codes per sign-in challenge for TOTP and backup codes. Once the limit is reached the challenge is rejected with TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE, and a new sign-in is required to try again.
During a rolling deploy, two-factor challenges issued by the previous version may prompt the user to sign in again; this clears once the deploy completes.
Updated dependencies [90d509e, 816d7f9, 570267c, 5953157]:
Fixed account-linking logs to route through the configured logger
better-authAPIError properties (#8734)Max-Age to be capped at expiresIn (#9621)For detailed changes, see CHANGELOG
@better-auth/i18nFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@adityachaudhary99, @dipan-ck, @sleepe229, @WilsonnnTan
Full changelog: v1.6.19...v1.6.20
#10121 21448b1 Thanks @adityachaudhary99! - OAuth account-linking and create-user error logs now respect a custom logger configured in betterAuth(), instead of always being written to the default console logger.
#9621 8ecf238 Thanks @dipan-ck! - Session refresh no longer emits a cookie Max-Age above the browser's 400-day ceiling when using a database without fractional-second precision.
#8734 930f534 Thanks @sleepe229! - declare inherited APIError properties to fix TypeScript inference errors
Updated dependencies []:
Added support for pre-binding device codes to a specific user in the device authorization plugin
better-authsendVerificationEmail errors not being surfaced to the client (#8863)last-login-method plugin (#9319)oauth-popup plugin leaking internal OAuth state keys into additionalData (#10067)For detailed changes, see CHANGELOG
authgenerate command not handling a directory path passed to --output (#9564)additionalField default values not being serialized correctly in the Drizzle schema generator (#10048)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/mongo-adapterFor detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
@better-auth/scimFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@brone1323, @bytaesu, @ChrisMGeo, @ElGauchooooo, @gustavovalverde, @ping-maxwell, @tsushanth, @Tushar-Khandelwal-2004
Full changelog: v1.6.18...v1.6.19
#10088 de4aa52 Thanks @bytaesu! - Session and account cache cookies near the browser's per-cookie size limit (for example with a long cookiePrefix or many cached fields) are now split into chunks instead of being silently dropped by the browser. A cache too large to fit even when chunked is skipped with a warning rather than failing the request, so reads fall back to the database.
#9995 b4b0266 Thanks @ElGauchooooo! - The device authorization plugin now accepts an optional user_id when issuing a device code via /device/code, pre-binding the code to that user. Only the bound user can approve or deny the code, so a publicly visible user code can no longer be claimed by someone else.
#10086 5bd5e1c Thanks @gustavovalverde! - Refresh-token rotation and token revocation, two-factor backup-code regeneration, device-code claiming, and organization invitation acceptance now work on Prisma. Concurrent or repeat requests in these flows could previously return an error on Prisma instead of the expected result.
On MongoDB servers older than 5.0, these flows and other guarded value updates (rate-limit window resets, API-key refills) no longer fail with an empty-update error.
@better-auth/core: incrementOne now reports a clear error when called with no increment and no set.
#9319 581f827 Thanks @ping-maxwell! - fix(last-login-method): include domain when clearing cross-subdomain cookies
#10067 8407885 Thanks @bytaesu! - The oauth-popup plugin now ignores internal OAuth state fields passed through its additionalData parameter, so additionalData only ever carries your own custom values.
#9555 c1a8a64 Thanks @ChrisMGeo! - Fix invalid OpenAPI output for Better Auth callback, session, and passkey routes so client generators can consume the schema.
#10071 635f190 Thanks @gustavovalverde! - Auth clients exported from wrapper packages can now be emitted in TypeScript declaration builds without extra type annotations.
#10070 a787e0b Thanks @gustavovalverde! - Single-use verification flows no longer hang on database adapters that use a one-connection pool. This fixes magic-link verification and similar token checks in connection-limited serverless database setups.
#9348 c2f718f Thanks @ping-maxwell! - fix: cookie cache fallback lookup
#8863 7d18175 Thanks @ping-maxwell! - sendVerificationEmail was invoked via runInBackgroundOrAwait, which could defer work when advanced.backgroundTasks.handler is configured (so the handler could return 200 before the email callback finished) and, in the default path, caught and logged errors without rethrowing. User callbacks that throw APIError (e.g. 429 from a rate limiter) were therefore not reliably reflected in the HTTP response (better-auth/better-auth#8757).
Now we await sendVerificationEmailFn so failures surface to the client with the correct status. The unauthenticated /send-verification-email path enforces a constant-time floor (500 ms) so that the response duration does not reveal whether the email belongs to a real unverified user.
Updated dependencies [0895993, 5bd5e1c, a787e0b]:
Fixed getCookieCache to return null for expired sessions instead of treating stale signed cookies as live sessions.
better-authgetCookieCache to return null for expired sessions instead of treating stale signed cookies as live sessions.<id>@reddit.invalid) to users with no email, preventing accidental matches with real mailboxes.internalAdapter.reserveVerificationValue to atomically record single-use markers, ensuring only one concurrent caller succeeds for replay-protected operations.incrementOne adapter method and SecondaryStorage.increment for atomic counter updates, enabling strict rate-limit and usage-counter enforcement under concurrent load./delete-user/callback to reject account deletion when the session has been revoked server-side (cookie-only session deployments are unaffected).consume method for custom storage backends to opt into strict enforcement.offline_access scope for refresh token usage.oneTap plugin or socialProviders.google) and reject tokens issued for other applications.set-active and revoke endpoints to only act on sessions the caller holds a signed cookie for, preventing unauthorized session manipulation./oauth2/endsession endpoint to reject cross-site logout requests that carry only a session cookie without a valid id_token_hint.mapProfileToUser available to supply a real one.For detailed changes, see CHANGELOG
@better-auth/ssotrustEmailVerified to treat only a boolean true or the string "true" as a verified email, rejecting the string "false" as unverified.For detailed changes, see CHANGELOG
@better-auth/memory-adapterupdate and delete no-ops on empty filters instead of modifying every row.For detailed changes, see CHANGELOG
@better-auth/oauth-providerFor detailed changes, see CHANGELOG
@better-auth/scimFor detailed changes, see CHANGELOG
@better-auth/api-keyFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterupdateMany to return the number of rows it affected, as the adapter contract specifies.For detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterconsumeOne compatibility with SQL Server.For detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
@better-auth/prisma-adapterdelete operation to surface errors instead of silently reporting success when the failure is not a missing-record error.For detailed changes, see CHANGELOG
@better-auth/redis-storageincrement method for strict enforcement.For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@GautamBytes
Full changelog: v1.6.17...v1.6.18
#9315 9ef7240 Thanks @GautamBytes! - fix OpenAPI requestBody generation for intersected and default-wrapped body schemas
#9583 b21a5f7 Thanks @GautamBytes! - Fix plugin-provided client methods and additional session fields not being inferred in composite monorepos.
Updated dependencies [b21a5f7]:
Added an experimental oauthPopup plugin for popup-based OAuth sign-in, enabling sign-in inside cross-site iframes by completing the OAuth flow in a po
better-authoauthPopup plugin for popup-based OAuth sign-in, enabling sign-in inside cross-site iframes by completing the OAuth flow in a popup and passing the session token back via the bearer plugin (#9890)getCookieCache to return null for an expired session instead of stale data, so middleware no longer treats an expired signed cookie as a live session.<id>@reddit.invalid) to users with no email, instead of one on the real reddit.com domain, preventing accidental mailbox matches. The address stays unverified, and mapProfileToUser can supply a real email.internalAdapter.reserveVerificationValue for atomic single-use markers, ensuring exactly one concurrent caller succeeds and the rest see the marker as already taken, hardening replay protection across all verification flows. Database-backed storage is atomic; secondary-storage-only mode is best-effort.incrementOne adapter method and SecondaryStorage.increment for atomic counter updates with conditional row guards, enabling strict enforcement of rate limits and usage counters. Adapters without native support fall back to a transaction-based approach./delete-user/callback to reject account deletion when the session has been revoked server-side, instead of proceeding within the cookie-cache window. Deployments that keep sessions only in the cookie are unaffected.consume method for strict enforcement.offline_access scope.addMember and add-team-member paths, preventing teams from exceeding their maximumMembersPerTeam cap, and ensured a rejected addMember does not create the organization member (#10002)sub or id field when mapProfileToUser derives the account id (#9987)admin.setUserPassword to create a credential account for users who only have social or magic-link accounts, enabling direct password assignment without manually modifying the account table (#9482)updateSession to accept custom session fields inferred from inferAdditionalFields (#9777)/get-session requests triggered by focus and other browser events, stabilized client hook data references to reduce unnecessary re-renders, and resolved session state getting stuck loading after unmounting during an in-flight request (#8760)id fields as required (#9704)updateMemberRole to reject unknown or malformed role values, validating them against configured static and dynamic roles (#9962)role.authorize control flow without changing existing authorization behavior (#9677)set-active and revoke endpoints to only act on sessions the caller holds a signed cookie for, preventing unauthorized activation or revocation of other sessions./oauth2/endsession endpoint to reject cross-site GET logout requests carrying only a session cookie, while leaving logout authenticated by a valid id_token_hint unaffected.For detailed changes, see CHANGELOG
@better-auth/api-keyFor detailed changes, see CHANGELOG
@better-auth/ssotrustEmailVerified to no longer treat the string "false" as a verified email, accepting only a boolean true or the string "true" as confirmation.For detailed changes, see CHANGELOG
auth$app/*, $env/*), Vite asset imports (?raw, ?url), and Cloudflare Workers (cloudflare:workers) virtual-module imports when loading the auth config (#9834)Unsupported() fields when regenerating the Prisma schema (#10011)BigInt or Int when bigint configuration changes (#9729)For detailed changes, see CHANGELOG
@better-auth/expotrustedOrigins (#9990)linkSocial (#9953)For detailed changes, see CHANGELOG
@better-auth/memory-adapterupdate and delete with an empty filter a no-op instead of affecting all rows, and made updateMany return the number of affected rows.For detailed changes, see CHANGELOG
@better-auth/scimFor detailed changes, see CHANGELOG
@better-auth/coreFor detailed changes, see CHANGELOG
@better-auth/drizzle-adapterupdateMany to return the number of rows it affected, as the adapter contract specifies.For detailed changes, see CHANGELOG
@better-auth/electronFor detailed changes, see CHANGELOG
@better-auth/kysely-adapterconsumeOne work on SQL Server.For detailed changes, see CHANGELOG
@better-auth/oauth-providerFor detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
@better-auth/prisma-adapterdelete errors instead of silently reporting success when a deletion fails for any reason other than the record being absent.For detailed changes, see CHANGELOG
@better-auth/redis-storageincrement method to Redis secondary storage.For detailed changes, see CHANGELOG
@better-auth/stripereturnUrl against trustedOrigins, and checked all subscriptions on organization deletion (#9971)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@arnnvv, @Bekacru, @bytaesu, @GautamBytes, @gustavovalverde, @SferaDev
Full changelog: v1.6.16...v1.6.17
#9993 baeaa00 Thanks @gustavovalverde! - When a team had a single open slot, accepting an invitation into it was wrongly rejected as over the member limit and left a dangling membership record. Two invitations accepted into a nearly-full team at the same time could also push it past its limit. Both are fixed.
#9482 3e99e6c Thanks @bytaesu! - admin.setUserPassword now creates a credential account when the target user does not have one, matching the behavior of resetPassword. Previously the call returned status: true without doing anything for users without an existing credential account (e.g., social-only or magic-link signups), so admins migrating users from another auth system or assigning an initial password to a social-only user can now do so directly without poking the account table.
96c78c3 Thanks @GautamBytes! - Downgrade expected auth validation failures from error logs to warnings.
#9993 baeaa00 Thanks @gustavovalverde! - Captcha provider verification requests now time out after 10 seconds and fail closed, so a slow or unreachable captcha provider can no longer tie up a request indefinitely.
#9993 baeaa00 Thanks @gustavovalverde! - A delete-account confirmation link can no longer delete the account more than once when its callback is opened concurrently.
#9991 0c3856f Thanks @gustavovalverde! - Completing account deletion through /delete-user/callback now fails when the session has been revoked server-side, instead of proceeding within the cookie-cache window. Deployments that keep sessions only in the cookie are unaffected.
#9993 baeaa00 Thanks @gustavovalverde! - Polling for a device-authorization token can no longer redeem the same approved device code more than once when several polls arrive together.
#9993 baeaa00 Thanks @gustavovalverde! - Submitting the same email OTP from several requests at once can no longer sign in more than once or gain extra tries beyond the attempt limit.
#10002 ed7b6c9 Thanks @gustavovalverde! - Adding a member to a team that is already at its maximumMembersPerTeam limit is now rejected on every path. addMember with a teamId and add-team-member previously skipped the limit that invitation acceptance enforced, so they could push a team over its cap. A rejected addMember no longer creates the organization member.
#9677 e0a768c Thanks @GautamBytes! - Refactor role.authorize control flow while preserving existing authorization behavior.
#9987 7343284 Thanks @bytaesu! - Generic OAuth sign-in works again for providers whose userinfo response has no sub or id field when mapProfileToUser derives the account id. An empty id field now falls back to sub.
#9991 0c3856f Thanks @gustavovalverde! - getCookieCache now returns null for an expired session instead of the stale session data. Middleware that calls it to gate access no longer treats an expired signed cookie as a live session.
#9993 baeaa00 Thanks @gustavovalverde! - The Have I Been Pwned plugin now checks submitted passwords against the breach database on more password-setting endpoints by default, including the email-OTP and phone-number reset-password routes and the admin create-user and set-user-password routes. A breached password can no longer be set through those routes when the plugin is enabled with its default paths.
#9987 7343284 Thanks @bytaesu! - Preserve the fresh account cookie issued while switching users in the same browser instead of expiring it from stale request cookie state.
#9991 0c3856f Thanks @gustavovalverde! - Expired MCP access tokens are no longer accepted. A protected MCP resource now rejects a bearer token once it has expired, both on the server and through the remote client. A refresh token is accepted only when the original authorization included the offline_access scope.
#9991 0c3856f Thanks @gustavovalverde! - The multi-session set-active and revoke endpoints now act only on the session the caller holds a signed cookie for. A request could previously activate or revoke a different session by naming its token in the request body without holding that session's cookie.
#9890 d9c526b Thanks @bytaesu! - Add an experimental oauthPopup plugin (with oauthPopupClient and signIn.popup) for popup-based OAuth sign-in. It lets an app sign in inside a cross-site iframe by completing OAuth in a popup and handing the session token back to the opener, where the bearer plugin authenticates with it. The API may change while it is experimental.
#9991 0c3856f Thanks @gustavovalverde! - The OIDC provider's RP-initiated logout endpoint (/oauth2/endsession) no longer logs a user out, or revokes their OAuth tokens, in response to a cross-site GET that carries only a session cookie. Logout authenticated by a valid id_token_hint is unaffected.
#10003 fdef997 Thanks @gustavovalverde! - Google One Tap now requires a configured Google client ID and rejects the sign-in callback when none is set. A Google ID token issued for a different application is no longer accepted. Set the client ID on the oneTap plugin or on socialProviders.google.
#9993 baeaa00 Thanks @gustavovalverde! - A one-time token can no longer be redeemed for a session more than once when redeemed concurrently.
#9993 baeaa00 Thanks @gustavovalverde! - A password reset token can no longer change the password more than once when used from several requests at the same time.
#9993 baeaa00 Thanks @gustavovalverde! - Submitting the same phone-number OTP from several requests at once can no longer sign in more than once or gain extra tries beyond the attempt limit.
#9993 baeaa00 Thanks @gustavovalverde! - Concurrent requests can no longer slip past the configured rate limit. The in-memory rate-limit store no longer grows without bound, and the database backend removes expired entries on its own. A custom rate-limit storage may implement a new optional consume method for strict enforcement; without it, the previous behavior is kept and a one-time warning is logged.
#9987 7343284 Thanks @bytaesu! - Deleting a team no longer breaks its pending invitations. The removed team is dropped from those invitations, which stay valid for their remaining teams or as plain organization-level invitations. Accepting an invitation that still references a missing team fails without consuming the invitation.
#9993 baeaa00 Thanks @gustavovalverde! - Add internalAdapter.reserveVerificationValue. It atomically records a single-use marker (such as a replay tombstone) so that exactly one of several concurrent callers succeeds and the rest observe that the marker is already taken. Database-backed verification storage is atomic; secondary-storage-only verification is best-effort.
#8760 8960f5f Thanks @gustavovalverde! - Session refreshes now avoid duplicate /get-session requests from focus and other browser session events. Client hooks keep stable data references when refetches return unchanged data, reducing unnecessary renders. Unmounting during an in-flight session request no longer leaves session state stuck in a loading state.
#9993 baeaa00 Thanks @gustavovalverde! - A Sign-In with Ethereum nonce can no longer be used to sign in more than once when submitted from several requests at the same time.
#9979 5c289b5 Thanks @SferaDev! - Stateless OAuth deployments can now read account info, access tokens, and refresh tokens after different server instances handle sign-in and later requests. Session refresh also keeps the OAuth account cookie instead of clearing it in that case.
#9990 1dbf5bb Thanks @gustavovalverde! - Hardens how requests are trusted across several flows. Rate limiting is now enforced even when a client IP cannot be determined, instead of being skipped. When baseURL is not configured, password-reset and verification links use the current request's host rather than the host of the first request the server handled, and a request-scoped trustedOrigins callback no longer affects other concurrent requests. The OAuth proxy, Google One Tap, and the Expo authorization proxy reject redirect and callback targets that are not in trustedOrigins. Google reCAPTCHA and Cloudflare Turnstile accept optional expectedAction and allowedHostnames to reject tokens minted for a different action or hostname. Server-side fetches reject additional reserved IPv6 ranges, and malformed redirect parameters return a 400 instead of a 500.
#9993 baeaa00 Thanks @gustavovalverde! - An expired two-factor sign-in challenge can no longer complete login with a valid TOTP, OTP, or backup code, and the same challenge can no longer create more than one session when verified concurrently.
#9993 baeaa00 Thanks @gustavovalverde! - Submitting the same two-factor OTP from several requests at once can no longer sign in more than once or gain extra tries beyond the attempt limit.
#9777 59e0ccb Thanks @GautamBytes! - Client updateSession calls now accept inferred custom session fields from inferAdditionalFields.
#9962 b803c61 Thanks @Bekacru! - Validate roles when updating an organization member. Roles are now normalized into individual tokens and checked against the configured static and dynamic roles, so unknown or malformed role values are rejected instead of being persisted.
Updated dependencies [baeaa00, baeaa00, baeaa00, 7343284, baeaa00, baeaa00, fdef997, baeaa00, baeaa00, fdef997, baeaa00, 1dbf5bb, fdef997]:
Fixed SIWE verification to bind the signed message to server state before creating a session, preventing acceptance of signatures produced for a diffe
better-authhd (hosted domain) enforcement to verify the hd claim on the verified ID token and callback profile, preventing accounts outside the configured Workspace domain from signing in.verifyAccessToken remote introspection to reject tokens with a missing or mismatching aud claim; set remoteVerify.allowMissingAudience: true to permit tokens where the introspection response legitimately omits aud./admin/create-user and /admin/update-user, and prevent data from overriding protected fields. (#9974)Origin and Referer headers against trustedOrigins even when requests carry no cookies. (#9973)/update-session to reject plugin-managed fields (activeOrganizationId, activeTeamId, impersonatedBy) with a 400 error; use their dedicated endpoints to change these values. (#9965)/update-session and account token routes to immediately reject deleted sessions when cookie cache is enabled alongside database or secondary storage. (#9967)/refresh-token to only trust the account cookie when its userId, providerId, and accountId match the resolved session user.sub.createInvitation and acceptInvitation to validate that all requested team IDs belong to the invitation's organization, preventing cross-organization team membership.oauth_client_id as the user email, preventing all users of the same app from sharing a single email address; a synthetic per-user address is now used when no real email is provided via mapProfileToUser.debug_token endpoint, requiring is_valid, a matching app_id, and a client secret for direct sign-in.For detailed changes, see CHANGELOG
@better-auth/oauth-providerauthorization_code from requesting client_credentials tokens./oauth2/continue to derive post-login gate completion from a server-issued session marker rather than the client-submitted postLogin flag.azp claim and a valid client on JWT access tokens, preventing session JWTs from being reported as active access tokens.For detailed changes, see CHANGELOG
@better-auth/ssoAuthnRequest handling to consume the request atomically, preventing replay attacks on concurrent requests. (#9972)For detailed changes, see CHANGELOG
@better-auth/api-key/api-key/create to verify the session against the authoritative store with disableCookieCache: true, preventing revoked sessions from being accepted within the cookie-cache window.For detailed changes, see CHANGELOG
@better-auth/electroncode_challenge_method values.For detailed changes, see CHANGELOG
@better-auth/scimlinkExistingUsers is set, changed org-scoped DELETE to deprovision the user rather than delete the global account, and added canGenerateToken to control SCIM token creation.For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@Bekacru, @gustavovalverde
Full changelog: v1.6.15...v1.6.16
#9974 cb1cbfa Thanks @Bekacru! - Guard protected user fields in the admin plugin behind their dedicated permissions. /admin/create-user now requires user:set-role when a role is supplied (top-level or via data.role), validates requested roles against the configured roles, requires user:ban for ban fields passed in data, and no longer lets data override email, name, or role. /admin/update-user now requires user:ban for banned/banReason/banExpires (revoking the user's sessions when banning and rejecting self-bans), requires the new user:set-email permission for email/emailVerified (with email validation, lowercasing, and uniqueness checks), and rejects password updates in favor of /admin/set-user-password. If you use a custom access control, add set-email to your statements and grant it (and ban) to roles that should be able to change those fields through update-user.
#9974 cb1cbfa Thanks @Bekacru! - Require a provider account id when signing in through generic OAuth. The default userinfo handler previously fell back to an empty string when the provider response had no sub (or id), and the callback never checked the resolved account id. With certain non-OIDC providers that omit sub, accounts could be stored under the same empty id and a later sign-in could resolve to an existing account. The generic OAuth callback now rejects sign-in when no account id can be resolved, the default userinfo handler returns no profile when neither sub nor id is present, and the built-in OAuth callback also rejects an empty account id.
#9974 cb1cbfa Thanks @Bekacru! - Scope organization invitation team IDs to the invited organization. createInvitation now validates that every requested teamId belongs to the invitation's organization regardless of whether teams.maximumMembersPerTeam is set, and acceptInvitation re-checks each stored team's organization before adding team membership. Previously, with the default unlimited team size, a team ID from another organization could be stored on an invitation and applied on acceptance.
#9973 87e7aa5 Thanks @gustavovalverde! - Email sign-in and sign-up now validate the Origin or Referer header against trustedOrigins even when the request carries no cookies. Requests that send no Origin/Referer header and no Fetch Metadata (such as curl or server-to-server clients) are unaffected. A non-browser client that sends an untrusted Origin/Referer without cookies now receives a 403 and must add that origin to trustedOrigins.
#9974 cb1cbfa Thanks @Bekacru! - Require /refresh-token to only trust the account cookie when its userId, providerId and (when supplied) accountId match the resolved session user.
#9967 893cf6c Thanks @gustavovalverde! - Deleting a session now immediately stops /update-session and the account token endpoints (/get-access-token, /refresh-token, /account-info) from accepting it, when cookie cache is enabled alongside a database or secondary storage. Before, these routes kept serving the deleted session from the cached cookie until the cache expired. Deployments that store the session only in the cookie are unaffected.
#9974 cb1cbfa Thanks @Bekacru! - Bind the SIWE signed message to server state before creating a session. Previously /siwe/verify only checked that a nonce row existed for the wallet address and then delegated entirely to verifyMessage. Since the documented verifyMessage (viem) performs signature recovery only — without inspecting the message body — a signature the wallet produced for a different message (an earlier nonce, another domain, or arbitrary content) could also satisfy verification against a freshly minted nonce.
The plugin now parses the ERC-4361 message itself and requires its nonce, domain, address, and chain ID to match the server-issued nonce and configured domain, and enforces the message's Expiration Time / Not Before bounds, before verifying the signature. message must now be a valid ERC-4361 message (which all standard SIWE clients produce); non-conforming or mismatched messages are rejected with a 401 (UNAUTHORIZED_SIWE_MESSAGE_MISMATCH, UNAUTHORIZED_SIWE_MESSAGE_EXPIRED, or UNAUTHORIZED_SIWE_MESSAGE_NOT_YET_VALID). verifyMessage implementations should continue to perform signature recovery only.
#9974 cb1cbfa Thanks @Bekacru! - Separate SSO provider ids from the account-linking provider namespace used for social/OAuth providers. Previously an SSO provider registered with an id matching a configured accountLinking.trustedProviders entry (e.g. google) was treated as a trusted provider and could implicitly link to an existing verified account with the same email.
SSO registration now rejects provider ids that collide with a configured social provider, a trustedProviders entry, or a reserved built-in id. In addition, the OIDC and SAML callbacks no longer derive trust from a trustedProviders name match — SSO trust comes solely from verified domain ownership (domainVerified). handleOAuthUserInfo gains a trustProviderByName option (default true, preserving social-provider behavior) that the SSO plugin sets to false.
#9965 5e49c56 Thanks @gustavovalverde! - Passing activeOrganizationId, activeTeamId, or impersonatedBy to /update-session now returns a 400. Change these plugin-managed session fields through their dedicated endpoints instead, such as organization.setActive.
Updated dependencies [cb1cbfa, cb1cbfa, cb1cbfa, cb1cbfa, cb1cbfa, cb1cbfa]:
Fixed the listSessions endpoint to properly enforce fresh-age session checks
better-authlistSessions endpoint to properly enforce fresh-age session checks (#9865)unbanUser, setRole, and adminUpdateUser to return USER_NOT_FOUND instead of a generic 500 when the target user does not exist (#9875)For detailed changes, see CHANGELOG
@better-auth/oauth-providerPOST support to the /oauth2/userinfo endpoint, allowing the access token to be passed in the Authorization header (#9937)hooks.before and hooks.after to run correctly when OAuth authorization resumes after sign-in, account selection, or consent (#9919)For detailed changes, see CHANGELOG
@better-auth/kysely-adapterFor detailed changes, see CHANGELOG
@better-auth/passkeygetAuthenticatorName(aaguid) and commonAuthenticatorNames so passkeys can display a friendly provider name like "1Password" or "Google Password Manager" (#9927)For detailed changes, see CHANGELOG
@better-auth/ssoERR_SUBJECT_UNCONFIRMED errors caused by clockSkew not being forwarded to samlify's ServiceProvider when validating SAML responses (#9748)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @ping-maxwell, @seebykilian, @WilsonnnTan, @zeroknowledge0x
Full changelog: v1.6.14...v1.6.15
#9875 1012b69 Thanks @WilsonnnTan! - The admin plugin's unbanUser, setRole and adminUpdateUser endpoints used to call internalAdapter.updateUser without checking that the target user existed, so when the caller passed an unknown id the underlying database error (for example Prisma's P2025) bubbled up as a generic HTTP 500. those endpoints now mirror the existing guard in banUser: look the user up via findUserById, and throw a clean NOT_FOUND (USER_NOT_FOUND) when no row is returned. Closes #9800.
#9865 ad60333 Thanks @ping-maxwell! - list-session endpoint now requires a fresh-age session check.
#9811 0933c05 Thanks @zeroknowledge0x! - Restore Kysely 0.28 and 0.29 compatibility for SQLite dialect introspection. The dialects now mirror Kysely's stable migration table names locally, avoiding strict ESM build failures in Turbopack without forcing consumers onto Kysely 0.29.
#9919 b0ddfd3 Thanks @gustavovalverde! - Run configured hooks through the whole OAuth sign-in flow
hooks.before / hooks.after configured on the auth instance now run for the OAuth authorization that continues after a user signs in, selects an account, or consents. They were being skipped there.
Headers or cookies a hooks.before sets before returning its own response are no longer dropped, and a hooks.after that throws an APIError no longer loses either its cookies or the error's headers.
Updated dependencies []:
Fixed Google One Tap authenticating the wrong user when the presented Google account was already linked to a different local user.
better-authnull values being rejected for optional fields in the generated database schema (#9841)getSessionCookie to prefer the __Secure- prefixed cookie over a non-secure leftover, preventing a stale cookie from shadowing the current session (#9806)For detailed changes, see CHANGELOG
@better-auth/ssoFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde
Full changelog: v1.6.13...v1.6.14
#9877 2d9781a Thanks @gustavovalverde! - Restore the normal emailed-invitation flow while documenting the stricter verification posture for organization invitations.
Client-side listUserInvitations now always requires a verified session email because it enumerates invitation IDs from session.user.email. The requireEmailVerificationOnInvitation option now controls recipient calls that carry an invitation ID (acceptInvitation, rejectInvitation, getInvitation). When unset, Better Auth keeps the emailed-invitation sign-up flow for built-in opaque invitation IDs, including the default generator or advanced.database.generateId: "uuid", and requires verified email when invitation IDs are externally controlled or predictable, such as advanced.database.generateId: "serial" / false or custom ID generation. Apps that expose invitation IDs outside the invited user's mailbox, expose organization invitation lists to members, or require stricter ownership proof should set requireEmailVerificationOnInvitation: true or require verified email before sign-in.
#9841 5a2d642 Thanks @bytaesu! - Optional fields (required: false) now accept null, not just omission. The
generated input validation previously rejected null even though the column is
nullable, so a nullable field could not be cleared by passing null.
#9845 13abc79 Thanks @gustavovalverde! - Harden redirect-URI validation across the OAuth provider plugins. isSafeUrlScheme and SafeUrlSchema no longer call URL.canParse, which is absent on some supported runtimes and could throw or silently disable the dangerous-scheme check. They now parse with a try/catch fallback. SafeUrlSchema also rejects redirect URIs that contain a fragment component, per RFC 6749 §3.1.2.
#9806 9d3450a Thanks @bytaesu! - getSessionCookie now prefers the __Secure- cookie when both it and a non-secure cookie are present, so the non-secure cookie no longer shadows the current session cookie.
Updated dependencies [13abc79]:
Fixed a high-severity XML injection vulnerability in signed SAML assertions by updating samlify to 2.13.1 (GHSA-34r5-q4jw-r36m)
better-authaccountInfo calls with an optional userId parameter, allowing trusted callers to read provider profiles without constructing session headers (#9813)viewBackupCodes is a server-only function not accessible via HTTP in its API documentation (#9822)storeStateStrategy defaulting to "cookie" instead of "database" when only secondaryStorage is configured, preventing oversized-cookie errors on platforms like AWS Lambda (#9591)updateUserInfoOnLink not being applied when linking accounts through the standard OAuth redirect flow (#8758)oidc-provider and mcp plugins accepting invalid redirect_uri schemes such as javascript: and data: (#9838)logo not accepting null, preventing users from clearing an existing logo on create and update (#9842)For detailed changes, see CHANGELOG
@better-auth/ssointernalAdapter helper methods that could silently match the wrong account or wipe all sessions for a user (#9818)samlify to 2.13.1 (GHSA-34r5-q4jw-r36m) (#9821)For detailed changes, see CHANGELOG
@better-auth/api-keyverifyApiKey rejecting keys created under a non-default configId when the request omitted configId (#9794)For detailed changes, see CHANGELOG
@better-auth/coreconsumeOne when an adapter's deleteMany returned a non-numeric value, now surfacing a clear error (#9831)For detailed changes, see CHANGELOG
@better-auth/expoFor detailed changes, see CHANGELOG
@better-auth/oauth-providerPOST /oauth2/register bypassing the clientPrivileges create check, allowing unauthorized dynamic client registration (#9837)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @Vishesh-Verma-07
Full changelog: v1.6.12...v1.6.13
#9305 e7eb45b Thanks @gustavovalverde! - feat(oauth): per-request additionalParams and loginHint parity across signIn.social, linkSocial, and signIn.sso
Unified escape hatch for customizing the provider authorization URL on a per-request basis. Previously, dynamic parameters like Google's access_type=offline / prompt=consent, Cognito's identity_provider=Google, or Microsoft's domain_hint could only be set as static server configuration.
signIn.social, linkSocial, and signIn.sso accept additionalParams: Record<string, string>. Values are appended to the authorization URL as query parameters.linkSocial also accepts loginHint, matching the surface of signIn.social and signIn.sso.OAuthProvider.createAuthorizationURL gains additionalParams in its input contract; every built-in provider forwards it to the shared helper.additionalParams with the config-level authorizationUrlParams; call-time wins on key collision.identityProvider?: string config option that maps to the identity_provider query parameter, avoiding magic strings.createAuthorizationURL helper silently drops any caller-supplied key in RESERVED_AUTHORIZATION_PARAMS (state, client_id, redirect_uri, response_type, code_challenge, code_challenge_method, scope). The request-body Zod schema rejects the same keys with 400, so misuse is visible at the edge rather than silently overriding security-critical parameters.wechat → appid, tiktok → client_key) additionally filter those keys so a caller cannot swap the configured OAuth app.atlassian → audience, notion → owner) are merged last so caller-supplied additionalParams cannot override them. Configured defaults that represent operator intent (e.g. Google include_granted_scopes, Cognito identityProvider) remain caller-overridable.signIn.sso rejects additionalParams with 400 when the resolved provider is SAML; the SAML AuthnRequest is signed and cannot carry caller-supplied query parameters, so silently dropping them would mislead integrators.ZodRecord handling to the OpenAPI generator so z.record() fields emit type: object with typed additionalProperties. Incidentally fixes a long-standing bug where additionalData was rendered as type: string.discord, roblox, zoom, and slack providers now delegate to the shared createAuthorizationURL helper and inherit its RFC behavior and reserved-key guard.tiktok and wechat keep their manual URL construction (non-standard OAuth2 parameter names and URL fragment requirements) but thread additionalParams with the same reserved-key filter.Closes #2351. Closes #5441. Closes #5592. Closes #5604. Supersedes #4992 and #5443.
#9657 1e5b808 Thanks @gustavovalverde! - Harden private_key_jwt and token endpoint client authentication, and add the helpers that make the fix structural.
@better-auth/core/oauth2 now exposes encodeBasicCredentials and decodeBasicCredentials, a round-trip-tested pair that follows RFC 6749 §2.3.1 (application/x-www-form-urlencoded each value, split on the first : only). The decoder accepts the scheme case-insensitively and tolerates one or more spaces before the credentials per RFC 7235 §2.1. client_secret_basic on the client side and the Better Auth OAuth provider on the server side both go through these helpers, so credentials containing reserved characters round-trip cleanly across the stack and headers like basic xxx or Basic xxx are accepted.
createPrivateKeyJwtClientAssertionGetter validates options eagerly. Unsupported algorithms (HS256, none), a JWK with no key material, and disagreement between an explicit algorithm and the JWK-embedded alg all throw at construction rather than on the first token request. signPrivateKeyJwtClientAssertion enforces the same checks for direct callers. Breaking: configurations that paired an unsupported JWK alg with a different explicit algorithm used to silently sign with the explicit option; they now fail at construction.
@better-auth/oauth-provider rejects empty jwks payloads at the schema layer (jwks: [] and jwks: { keys: [] }) so the documented client metadata contract matches what checkOAuthClient already enforces at runtime. Schema consumers (TypeScript, OpenAPI, generated SDKs) now see the constraint.
The SSO private_key_jwt flow redirects with error_description=no_private_key_available when a resolvePrivateKey callback returns no privateKeyJwk or privateKeyPem. The redirect path previously short-circuited only when the resolver was absent entirely; an empty resolver return fell through into an internal signing error.
better-auth/test adds getHttpTestInstance, a counterpart to getTestInstance that binds a real HTTP listener on an OS-assigned port and constructs the auth instance against the discovered URL. It removes the temp-server-then-rebind race that test files have been individually copy-pasting.
#9301 03e6c94 Thanks @gustavovalverde! - Add allowIdpInitiated to GenericOAuthConfig and SSO OIDCConfig to support providers that initiate OAuth without a state parameter (e.g. Clever). When enabled, stateless callbacks restart the OAuth flow server-side with fresh state and PKCE, preserving CSRF protection. Also hardens parseState against undefined request bodies on GET callbacks.
#9845 13abc79 Thanks @gustavovalverde! - Harden redirect-URI validation across the OAuth provider plugins. isSafeUrlScheme and SafeUrlSchema no longer call URL.canParse, which is absent on some supported runtimes and could throw or silently disable the dangerous-scheme check. They now parse with a try/catch fallback. SafeUrlSchema also rejects redirect URIs that contain a fragment component, per RFC 6749 §3.1.2.
Updated dependencies [e7eb45b, 03e6c94, 1e5b808, 13abc79]:
Fixed field index ordering in getMigration migrations.
better-authgetMigration migrations. (#9691)changeEmail to return an error when emailVerification.sendVerificationEmail is missing, and URL-encoded callbackURL in verify-email links. (#9614)callbackURL URL-encoding in verify-email links for OAuth account linking and username sign-in. (#9792)role.authorize to reject empty action lists and correctly evaluate OR conditions on unknown resources. (#9603)AdminClientOptions and OrganizationClientOptions. (#9642)parseJSON to properly decode escape sequences in quoted strings. (#9617); separators, preventing users behind certain proxies from being treated as logged-out. (#9543)getTrustedOrigins to respect the dynamic baseURL protocol option. (#9644)sendVerificationEmail callback. (#9619)accessTokenExpiresIn config option to genericOAuth for providers that omit expires_in in their token response. (#9799)user_creation_failed. (#9723)state_mismatch when production and preview environments use different secrets. (#9385)state_not_found, state_invalid, state_mismatch) instead of the generic please_restart_the_process code. (#9788)errorCallbackURL instead of the default error page. (#9789)operationIds for endpoints that expose multiple HTTP methods. (#9721)deleteOrganization and removeMember to roll back on failure instead of leaving orphaned rows. (#9630)session_token and session_data cookies to be captured and replayed to bypass 2FA when cookie caching is enabled. (#9639)createUser endpoint. (#9464)For detailed changes, see CHANGELOG
@better-auth/oauth-providerregistration_endpoint to be hidden from .well-known metadata unless dynamic client registration is enabled. (#9448)client_secret values containing colons. (#9601)NOT_FOUND when the referenced client no longer exists. (#9600)For detailed changes, see CHANGELOG
@better-auth/coretoCamelCase, toSnakeCase, toPascalCase, and toKebabCase utilities to @better-auth/core/utils/string. (#9727)verifyAccessToken to return proper unauthorized errors for invalid token verification failures. (#9655)For detailed changes, see CHANGELOG
@better-auth/ssoerrorCallbackURL instead of returning a JSON error. (#9702)For detailed changes, see CHANGELOG
@better-auth/drizzle-adapterFor detailed changes, see CHANGELOG
@better-auth/passkeytransports is undefined. (#9746)For detailed changes, see CHANGELOG
@better-auth/api-keyTS4023 declaration emit errors by adding better-call as a peer dependency. (#9759)For detailed changes, see CHANGELOG
@better-auth/electron;, ", or \. (#9631)For detailed changes, see CHANGELOG
@better-auth/kysely-adapterBunSqliteDialect, NodeSqliteDialect) incorrectly reporting tables as views. (#9615)For detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @chdanielmueller, @cyphercodes, @gustavovalverde, @jsj, @kgarg2468, @Paola3stefania, @ping-maxwell, @reslear
Full changelog: v1.6.11...v1.6.12
Fixed an invitation takeover vulnerability by enabling requireEmailVerificationOnInvitation by default and extending the verification gate to getInvit…
better-authchange-email-disabled response to help clients identify the rejection reason (#8948)onLinkAccount when email verification triggers auto sign-in (#9548)oidc-provider and mcp plugins to require client_secret for confidential clients on refresh token grants and use constant-time secret comparison (#9576)oidc-provider and mcp plugins to follow OAuth 2.1: removed "none" from advertised signing algorithms, defaulted plain PKCE off, and rejected incomplete PKCE parameters (#9575)requireEmailVerificationOnInvitation by default and extending the verification gate to getInvitation and listUserInvitations (#9577)For detailed changes, see CHANGELOG
@better-auth/oauth-providerunique constraint on oauthRefreshToken.tokenFor detailed changes, see CHANGELOG
@better-auth/coreadvanced.ipAddress.ipv6Subnet to accept any valid IPv6 prefix length (0-128) instead of a narrow set of values (#9545)For detailed changes, see CHANGELOG
@better-auth/scimgenerateSCIMToken to reject providerId values that collide with built-in account providers, preventing tokens from authenticating against unintended accounts (#9579)For detailed changes, see CHANGELOG
@better-auth/ssoFor detailed changes, see CHANGELOG
authclaimOne adapter primitive for consuming database rows without race conditions (#9560)claimOne adapter primitive to consumeOne and added internalAdapter.consumeVerificationValue for atomically consuming verification rows (#9568)For detailed changes, see CHANGELOG
@better-auth/api-keyFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@dipan-ck, @GautamBytes, @gustavovalverde, @Kvizas, @ping-maxwell, @stewartjarod
Full changelog: v1.6.10...v1.6.11
Exposed refreshUserSessions on the internal adapter
better-authrefreshUserSessions on the internal adapter (#7764)POST /sign-in/social mis-declaring required fields (#9268)useSession not revalidating after admin impersonation starts or stops (#9402)Set-Cookie headers being emitted on redirect responses from social sign-in and magic-link endpoints (#9497)emailAndPassword.autoSignIn is false (#8839)TypeError caused by non-ASCII characters in OAuth error descriptions on redirect (#9065)internalAdapter.deleteAccount parameter from accountId to id to reflect that it queries by primary key (#9503)undefined id (#9456)cancelPendingInvitationsOnReInvite having no effect, where re-inviting the same email always returned USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION (#9453)additionalFields in the organization plugin (#9349)useActiveMemberRole retaining a previous user's role after sign-out in SPA flows (#9440)setActiveTeam to only accept teams from the currently active organization (#9239)authClient.siwe.getNonce() as a compatibility alias for the SIWE nonce endpoint (#9461)callbackURL being ignored on signIn.username, so it now redirects correctly like signIn.email (#9475)For detailed changes, see CHANGELOG
@better-auth/oauth-providersessionId typing in refresh token types to be optional, matching the schema (#9324)prompt=login consent continuations not completing after a forced loginprompt=login not being honored after consent continuation, preventing session bypass (#9344)For detailed changes, see CHANGELOG
@better-auth/stripeonSubscriptionUpdate to receive the raw stripeSubscription object, and fixed onSubscriptionCancel to receive the post-update subscription row instead of a stale snapshot (#9354)getCheckoutSessionParams overriding internally managed Stripe Checkout Session fields such as success_url, cancel_url, customer, and line_items (#9481)onSubscriptionDeleted, onTrialEnd, and onTrialExpired receiving a stale pre-update subscription snapshot instead of the post-update row (#9356)getCheckoutSessionParams overriding free trial and internal metadata, which could hide trial periods and create duplicate subscription rows on webhook (#9474)For detailed changes, see CHANGELOG
@better-auth/api-keyapi.verifyApiKey not validating the key's configId against the request body (#9393)For detailed changes, see CHANGELOG
@better-auth/coreFor detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
@better-auth/sso/sso/saml2/sp/metadata throwing NOT_FOUND for providers configured via defaultSSO (#9398)For detailed changes, see CHANGELOG
authauth init generating broken MySQL and PostgreSQL Kysely database configs (#9455)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @Craga89, @cyphercodes, @dipan-ck, @dvanmali, @GautamBytes, @gustavovalverde, @IcanDivideBy0, @jaydeep-pipaliya, @mausic, @onmax, @ping-maxwell, @programming-with-ia, @zllovesuki
Full changelog: v1.6.9...v1.6.10
#8339 1e0f26d Thanks @ping-maxwell! - fix(captcha): breaks email-otp flow
#9484 8c1e917 Thanks @ping-maxwell! - fix: warn for cookie-plugin being last in array
#9437 b2d655c Thanks @cyphercodes! - Allow organization invitation role input types to accept dynamic access control roles.
#9497 09f1327 Thanks @bytaesu! - Endpoints that set cookies before redirecting (such as social sign-in
callbacks and magic-link verification) no longer emit each Set-Cookie
entry twice on the response.
#9387 906b7b3 Thanks @bytaesu! - The bearer plugin now produces a single entry per cookie name when merging
its session token into the request Cookie header. Previously the merged
header could carry two entries for the same name if the request already
had a stale session cookie, which would surface to downstream code that
picks the first occurrence.
#9475 e9c978e Thanks @jaydeep-pipaliya! - fix(username): respect callbackURL on /sign-in/username
The endpoint accepted a callbackURL body field but ignored it, so
authClient.signIn.username({ ..., callbackURL }) silently did nothing
while authClient.signIn.email redirected as expected. The handler now
sets a Location header when callbackURL is provided and returns
{ redirect, url } alongside token/user, matching the email flow.
#9440 e71aad3 Thanks @cyphercodes! - Clear organization active hook state after sign-out so useActiveMemberRole does not retain a previous user's role in SPA sign-out/sign-in flows.
#9402 80a655d Thanks @onmax! - Revalidate the client session after admin impersonation starts or stops.
#9503 15ff28a Thanks @bytaesu! - internalAdapter.deleteAccount parameter renamed from accountId to id to reflect that it queries by primary key, not the accountId column. No runtime behavior change.
#9268 88a7c67 Thanks @ping-maxwell! - fix: openAPI schema for POST /sign-in/social mis-declares required fields
#8839 9a7b51d Thanks @dipan-ck! - Apply email enumeration protection when emailAndPassword.autoSignIn is false. Duplicate sign-ups now return a synthetic user (token: null) and trigger onExistingUserSignUp, and new sign-ups skip auto sign-in (token: null)—even without requireEmailVerification, aligning with the docs.
#9065 1b25902 Thanks @ping-maxwell! - non-ASCII error_description in generic-oauth callback routes causes TypeError on redirect
#9349 cf59136 Thanks @ping-maxwell! - fix(organization): re-export field types to prevent TS2742 with additionalFields
#9453 a597ee0 Thanks @mausic! - The organization plugin's cancelPendingInvitationsOnReInvite option now actually cancels the prior pending invitation when re-inviting the same email. Previously the option had no effect — re-inviting always failed with USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION
#9456 fc02ced Thanks @cyphercodes! - Reject OAuth callbacks when provider user info omits the account id to avoid linking accounts under the literal undefined id.
#9461 9f1ef1f Thanks @cyphercodes! - Expose authClient.siwe.getNonce() as a compatibility alias for the SIWE nonce endpoint.
#9369 36ef808 Thanks @ping-maxwell! - fix: incorrect email casing across one-tap, email-otp & email-verification
#9239 c1336c5 Thanks @GautamBytes! - Fix organization.setActiveTeam so it only accepts teams from the current active organization.
#7764 3a9a2c3 Thanks @programming-with-ia! - chore: expose refreshUserSessions on internal adapter
#9521 fde0432 Thanks @ping-maxwell! - fix: improve link accessibility issues
Updated dependencies [2220a6d]:
Fixed instrumentation resolution in the adapter factory so edge and browser environments correctly use the pure variant
better-authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@erquhart
Full changelog: v1.6.8...v1.6.9
815ecf6]:
Fixed mapProfileToUser fallback for OAuth providers that may omit email from their profile response
better-authmapProfileToUser fallback for OAuth providers that may omit email from their profile response (#9331)id through beforeCreateTeam and beforeCreateInvitation hooks (#9253)For detailed changes, see CHANGELOG
@better-auth/oauth-providerstate parameter (#9328)For detailed changes, see CHANGELOG
@better-auth/passkeyexactOptionalPropertyTypes compiler option (#9270)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@baptisteArno, @gustavovalverde, @ping-maxwell
Full changelog: v1.6.7...v1.6.8
#9253 856ab24 Thanks @baptisteArno! - fix(organization): allow passing id through beforeCreateTeam and beforeCreateInvitation
Mirrors #4765 for teams and invitations: adapter.createTeam and adapter.createInvitation now pass forceAllowId: true, so ids returned from the respective hooks survive the DB insert.
#9331 9aa8e63 Thanks @gustavovalverde! - fix(oauth): support mapProfileToUser fallback for providers that may omit email
Social sign-in with OAuth providers that may return no email address (Discord phone-only accounts, Apple subsequent sign-ins, GitHub private emails, Facebook, LinkedIn, and Microsoft Entra ID managed users) can now be unblocked by synthesizing an email inside mapProfileToUser. Rejection logger messages now point at this workaround and at the new "Handling Providers Without Email" docs section.
Provider profile types now reflect where email can be null or absent:
DiscordProfile.email is string | null and optional (absent when the email scope is not granted)AppleProfile.email is optionalGithubProfile.email is string | nullFacebookProfile.email is optionalFacebookProfile.email_verified is optional (Meta's Graph API does not include this field)LinkedInProfile.email is optionalLinkedInProfile.email_verified is optionalMicrosoftEntraIDProfile.email is optionalTypeScript consumers who previously dereferenced profile.email directly inside mapProfileToUser will see a compile error that matches the runtime reality; use a nullish-coalescing fallback (profile.email ?? ...) or null-check the field.
Sign-in still rejects with error=email_not_found (social callback) or error=email_is_missing (Generic OAuth plugin) when neither the provider nor mapProfileToUser produces an email. First-class support for users without an email, keyed on (providerId, accountId) per OpenID Connect Core §5.7, is tracked in #9124.
Updated dependencies [9aa8e63]:
Added support for an array of client IDs as the ID token audience in social providers
better-authAPIError is thrown (#9211)./instrumentation module in those environments (#9281)callbackOnVerification not being called when updatePhoneNumber is enabled (#4894)For detailed changes, see CHANGELOG
@better-auth/oauth-providerAuthorization header from request context when using auth.api (#9244)For detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@gustavovalverde, @Kinfe123, @ouwargui, @ramonclaudio, @stewartjarod, @TanishValesha
Full changelog: v1.6.6...v1.6.7
#9211 307196a Thanks @stewartjarod! - Preserve Set-Cookie headers accumulated on ctx.responseHeaders when an endpoint throws APIError. Cookie side-effects from deleteSessionCookie (and any ctx.setCookie / ctx.setHeader calls before the throw) are no longer silently discarded on the error path.
#9292 4f373ee Thanks @gustavovalverde! - Accept an array of Client IDs on providers that verify ID tokens by audience (Google, Apple, Microsoft Entra, Facebook, Cognito). The first entry is used for the authorization code flow; all entries are accepted when verifying an ID token's aud claim, so a single backend can serve Web, iOS, and Android clients with their platform-specific Client IDs.
socialProviders: {
google: {
clientId: [
process.env.GOOGLE_WEB_CLIENT_ID!,
process.env.GOOGLE_IOS_CLIENT_ID!,
process.env.GOOGLE_ANDROID_CLIENT_ID!,
],
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
}
Passing a single string keeps working; no migration needed.
Also exports getPrimaryClientId from @better-auth/core/oauth2 for provider authors: it returns the primary Client ID (the raw string, or the entry at array index 0), paired with clientSecret for the authorization code flow. Providers now reject empty arrays, empty strings, and missing config at sign-in time instead of silently producing a malformed authorization URL. Google, Apple, and Facebook require both clientId and clientSecret because each of those providers mandates a client secret for their server-side code exchange. Microsoft Entra and Cognito only require clientId, since both support public-client flows with PKCE alone (no secret).
#9293 e1b1cfc Thanks @gustavovalverde! - Guard against c.body being undefined in parseState. Callback requests that arrive as GET leave c.body unset in some runtimes, which caused c.body.state to throw a TypeError before the existing error redirect could run. The state lookup now short-circuits on the query parameter and falls back to c.body?.state safely, so a callback without a state parameter redirects to the error page instead of crashing.
#4894 d053a45 Thanks @Kinfe123! - Fire callbackOnVerification when a phone number is verified with updatePhoneNumber: true. The callback previously only ran on initial verification, so consumers relying on it (e.g. to sync verified numbers to an external system) would miss the event when an authenticated user changed their number.
Updated dependencies [307196a, 4a180f0, 4f373ee]:
Fixed several SSRF vulnerabilities by unifying host classification and closing loopback bypass vectors across packages
better-authPartitioned attribute when forwarding Set-Cookie headers (#9235)disableRefresh query parameter in custom session validation (#9214)updateUser({ phoneNumber: null }) (#9219)For detailed changes, see CHANGELOG
@better-auth/coremapConcurrent, a bounded-concurrency async utility, at @better-auth/core/utils/async (#9227)@opentelemetry/api an optional peer dependency (#9111)For detailed changes, see CHANGELOG
@better-auth/api-keyFor detailed changes, see CHANGELOG
@better-auth/expoSecureStore on app startup, eliminating the login screen flash for returning users (#8953)For detailed changes, see CHANGELOG
@better-auth/oauth-providerFor detailed changes, see CHANGELOG
@better-auth/ssoFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @gustavovalverde, @jonathansamines, @ping-maxwell, @terijaki
Full changelog: v1.6.5...v1.6.6
#9214 4debfb6 Thanks @ping-maxwell! - fix(custom-session): use coerced boolean for disableRefresh query param validation
#9235 9ea7eb1 Thanks @bytaesu! - Preserve the Partitioned attribute when the customSession plugin and framework integrations forward Set-Cookie headers.
#9266 ab4c10f Thanks @ping-maxwell! - fix(organization): infer team additional fields correctly
#9219 a61083e Thanks @bytaesu! - Allow removing a phone number with updateUser({ phoneNumber: null }). The verified flag is reset atomically. Changing to a different number still requires OTP verification through verify({ updatePhoneNumber: true }).
#9226 e64ff72 Thanks @gustavovalverde! - Consolidate host/IP classification behind @better-auth/core/utils/host and close several loopback/SSRF bypasses that the previous per-package regex checks missed.
Electron user-image proxy: SSRF bypasses closed (@better-auth/electron). fetchUserImage previously gated outbound requests with a bespoke IPv4/IPv6 regex that missed multiple vectors. All of the following were reachable in production and are now blocked:
http://tenant.localhost/ and other *.localhost names (RFC 6761 reserves the entire TLD for loopback).http://[::ffff:169.254.169.254]/ (IPv4-mapped IPv6 to AWS IMDS, the classic SSRF bypass).http://metadata.google.internal/, http://metadata.goog/ (GCP instance metadata).http://instance-data/, http://instance-data.ec2.internal/ (AWS IMDS alternate FQDNs).http://100.100.100.200/ (Alibaba Cloud IMDS; lives in RFC 6598 shared address space 100.64/10, which the old regex did not cover).http://0.0.0.0:PORT/ (the Linux/macOS kernel routes the unspecified address to loopback: Oligo's "0.0.0.0 Day").http://[fc00::...]/, http://[fd00::...]/ (IPv6 ULA per RFC 4193) and IPv6 link-local fe80::/10, neither of which the regex recognized.Documentation ranges (RFC 5737 / RFC 3849), benchmarking (198.18/15), multicast, and broadcast are also now rejected.
better-auth: 0.0.0.0 is no longer treated as loopback. The previous isLoopbackHost implementation in packages/better-auth/src/utils/url.ts classified 0.0.0.0 alongside 127.0.0.1 / ::1 / localhost. 0.0.0.0 is the unspecified address, not loopback; treating it as such lets browser-origin requests reach localhost-bound dev services (Oligo's "0.0.0.0 Day"). The helper now accepts the full 127.0.0.0/8 range and any *.localhost name, and rejects 0.0.0.0.
better-auth: trusted-origin substring hardening. getTrustedOrigins previously used host.includes("localhost") || host.includes("127.0.0.1") when deciding whether to add an http:// variant for a dynamic baseURL.allowedHosts entry. Misconfigurations like evil-localhost.com or 127.0.0.1.nip.io would incorrectly gain an HTTP origin in the trust list. The check now uses the shared classifier, so only real loopback hosts get the HTTP variant.
@better-auth/oauth-provider: RFC 8252 compliance.
127.0.0.0/8 range (not just 127.0.0.1) plus [::1], with port-flexible comparison. Port-flexible matching is limited to IP literals; DNS names such as localhost continue to use exact-string matching per §8.3 ("NOT RECOMMENDED" for loopback).validateIssuerUrl uses the shared loopback check rather than a two-hostname literal comparison.New module: @better-auth/core/utils/host. Exposes classifyHost, isLoopbackIP, isLoopbackHost, and isPublicRoutableHost. One RFC 6890 / RFC 6761 / RFC 8252 implementation that handles IPv4, IPv6 (including bracketed literals, zone IDs, IPv4-mapped addresses, and 6to4 / NAT64 / Teredo tunnel forms with embedded-IPv4 recursion), and FQDNs, with a curated cloud-metadata FQDN set. All bespoke loopback/private/link-local checks across the monorepo now route through it.
Updated dependencies [b5742f9, a844c7d, e64ff72]:
Clarified recommended production usage for the test utils plugin
better-auth/change-password and /revoke-other-sessions (#9087)For detailed changes, see CHANGELOG
@better-auth/oauth-provider@better-auth/oauth-provider where unprivileged authenticated users could create OAuth clients when deployments relied on clientPrivileges to restrict client creation.@better-auth/oauth-provider@1.6.5.1.7.0-beta.0 and 1.7.0-beta.1) remains affected until a fixed beta release is published.For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@GautamBytes, @ramonclaudio
Full changelog: v1.6.4...v1.6.5
#9119 938dd80 Thanks @GautamBytes! - clarify recommended production usage for the test utils plugin
#9087 0538627 Thanks @ramonclaudio! - fix(client): refetch session after /change-password and /revoke-other-sessions
Updated dependencies []:
Fixed forceAllowId UUIDs set in database hooks being ignored on PostgreSQL adapters when advanced.database.generateId is set to "uuid"
better-authforceAllowId UUIDs set in database hooks being ignored on PostgreSQL adapters when advanced.database.generateId is set to "uuid" (#9068)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@GautamBytes, @gustavovalverde
Full changelog: v1.6.3...v1.6.4
#9205 9aed910 Thanks @gustavovalverde! - fix(two-factor): revert enforcement broadening from #9122
Restores the pre-#9122 enforcement scope. 2FA is challenged only on /sign-in/email, /sign-in/username, and /sign-in/phone-number, matching the behavior that shipped through v1.6.2. Non-credential sign-in flows (magic link, email OTP, OAuth, SSO, passkey, SIWE, one-tap, phone-number OTP, device authorization, email-verification auto-sign-in) are no longer gated by a 2FA challenge by default.
A broader enforcement scope with per-method opt-outs and alignment to NIST SP 800-63B-4 authenticator assurance levels is planned for a future minor release.
#9068 acbd6ef Thanks @GautamBytes! - Fix forced UUID user IDs from create hooks being ignored on PostgreSQL adapters when advanced.database.generateId is set to "uuid".
#9165 39d6af2 Thanks @gustavovalverde! - chore(adapters): require patched drizzle-orm and kysely peer versions
Narrows the drizzle-orm peer to ^0.45.2 and the kysely peer to ^0.28.14. Both new ranges track the minor line that carries the vulnerability fix and nothing newer, so the adapters only advertise support for versions that have actually been tested against. Consumers on older ORM releases see an install-time warning and can upgrade alongside the adapter; the peer is marked optional, so installs do not hard-fail.
Updated dependencies [39d6af2]:
Fixed prototype pollution vulnerability when merging user-supplied metadata in the Stripe plugin
better-authoperationId for the requestPasswordResetCallback endpoint in the OpenAPI spec (#9072)baseURL resolution from request headers for direct auth.api calls (#9113)isMounted race condition that caused excessive requests per second in the client (#9078)storeBackupCodes storage strategy after verification (#7231)For detailed changes, see CHANGELOG
@better-auth/oauth-providercustomTokenResponseFields callback for injecting custom fields into token endpoint responses, and hardened authorization code validation (#9118)baseURL resolution for direct auth.api calls and plugin metadata helpers (#9131)For detailed changes, see CHANGELOG
@better-auth/ssoFor detailed changes, see CHANGELOG
@better-auth/stripeFor detailed changes, see CHANGELOG
authFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @Byte-Biscuit, @gustavovalverde, @Oluwatobi-Mustapha, @ping-maxwell, @ramonclaudio
Full changelog: v1.6.2...v1.6.3
#9131 5142e9c Thanks @gustavovalverde! - harden dynamic baseURL handling for direct auth.api.* calls and plugin metadata helpers
Direct auth.api.* calls
APIError with a clear message when the baseURL can't be resolved (no source and no fallback), instead of leaving ctx.context.baseURL = "" for downstream plugins to crash on.allowedHosts mismatches on the direct-API path to APIError.advanced.trustedProxyHeaders on the dynamic path (default true, unchanged). Previously x-forwarded-host / -proto were unconditionally trusted with allowedHosts; they now go through the same gate as the static path. The default flip to false ships in a follow-up PR.resolveRequestContext rehydrates trustedProviders and cookies per call (in addition to trustedOrigins). User-defined trustedOrigins(req) / trustedProviders(req) callbacks receive a Request synthesized from forwarded headers when no full Request is available.http for loopback hosts (localhost, 127.0.0.1, [::1], 0.0.0.0) on the headers-only protocol fallback, so local-dev calls don't silently resolve to https://localhost:3000.hasRequest uses isRequestLike, which now rejects objects that spoof Symbol.toStringTag without a real url / headers.get shape.Plugin metadata helpers
oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata, oAuthDiscoveryMetadata, and oAuthProtectedResourceMetadata forward the incoming request to their chained auth.api calls, so issuer and discovery URLs reflect the request host on dynamic configs.withMcpAuth forwards the incoming request to getMcpSession, threads trustedProxyHeaders, and emits a bare Bearer challenge when baseURL can't be resolved (instead of Bearer resource_metadata="undefined/...").metadataResponse in @better-auth/oauth-provider normalizes headers via new Headers() so callers can pass Headers, tuple arrays, or records without silently dropping entries.#9122 484ce6a Thanks @gustavovalverde! - fix(two-factor): enforce 2FA on all sign-in paths
The 2FA after-hook now triggers on any endpoint that creates a new session, covering magic-link, OAuth, passkey, email-OTP, SIWE, and all future sign-in methods. Authenticated requests (session refreshes, profile updates) are excluded.
#7231 f875897 Thanks @Byte-Biscuit! - fix(two-factor): preserve backup codes storage format after verification
After using a backup code, remaining codes are now re-saved using the same storeBackupCodes strategy (plain, encrypted, or custom) configured by the user. Previously, codes were always re-encrypted with the built-in symmetric encryption, breaking subsequent verifications for plain or custom storage modes.
#9072 6ce30cf Thanks @ramonclaudio! - fix(api): align top-level operationId on requestPasswordResetCallback with the OpenAPI resetPasswordCallback
#8389 f6428d0 Thanks @Oluwatobi-Mustapha! - fix(open-api): correct get-session nullable schema for OAS 3.1
#9078 9a6d475 Thanks @ping-maxwell! - fix(client): prevent isMounted race condition causing many rps
#9113 513dabb Thanks @bytaesu! - resolve dynamic baseURL from request headers on direct auth.api calls
#8926 c5066fe Thanks @bytaesu! - omit quantity for metered prices in checkout and upgrades
#9084 5f84335 Thanks @bytaesu! - support Stripe SDK v21 and v22
Updated dependencies [93d3871]:
Updated dependencies []:
Prevented unverified TOTP enrollment from blocking sign-in
better-authMigration: Schema migration required.
Add the
verifiedcolumn to thetwoFactortable, then regenerate/apply your ORM migration.
- Prisma: run
npx auth@latest generate, thennpx prisma migrate dev(ornpx prisma db push) andnpx prisma generate.- Drizzle: run
npx auth@latest generate, thennpx drizzle-kit generateandnpx drizzle-kit migrate.
Existing rows do not need a backfill because the column defaults to
true.
nextCookies() by replacing cookie probe with header-based RSC detection (#9059)RelayState in signed SAML AuthnRequests (#9058)For detailed changes, see CHANGELOG
@better-auth/oauth-providerskip_consent at schema level in dynamic client registration (#8998)For detailed changes, see CHANGELOG
@better-auth/ssoFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@aarmful, @cyphercodes, @dvanmali, @gustavovalverde, @jaydeep-pipaliya, @ping-maxwell
Full changelog: v1.6.1...v1.6.2
#8949 9deb793 Thanks @ping-maxwell! - security: verify OAuth state parameter against cookie-stored nonce to prevent CSRF on cookie-backed flows
#8983 2cbcb9b Thanks @jaydeep-pipaliya! - fix(oauth2): prevent cross-provider account collision in link-social callback
The link-social callback used findAccount(accountId) which matched by account ID across all providers. When two providers return the same numeric ID (e.g. both Google and GitHub assign 99999), the lookup could match the wrong provider's account, causing a spurious account_already_linked_to_different_user error or silently updating the wrong account's tokens.
Replaced with findAccountByProviderId(accountId, providerId) to scope the lookup to the correct provider, matching the pattern already used in the generic OAuth plugin.
#9059 b20fa42 Thanks @gustavovalverde! - fix(next-js): replace cookie probe with header-based RSC detection in nextCookies() to prevent infinite router refresh loops and eliminate leaked __better-auth-cookie-store cookie. Also fix two-factor enrollment flows to set the new session cookie before deleting the old session.
#9058 608d8c3 Thanks @gustavovalverde! - fix(sso): include RelayState in signed SAML AuthnRequests per SAML 2.0 Bindings §3.4.4.1
authnRequestsSigned: true without a private key now throws instead of silently sending unsigned requests.#8772 8409843 Thanks @aarmful! - feat(two-factor): include enabled 2fa methods in sign-in redirect response
The 2FA sign-in redirect now returns twoFactorMethods (e.g. ["totp", "otp"]) so frontends can render the correct verification UI without guessing. The onTwoFactorRedirect client callback receives twoFactorMethods as a context parameter.
otpOptions.sendOTP is configured.#8711 e78a7b1 Thanks @aarmful! - fix(two-factor): prevent unverified TOTP enrollment from gating sign-in
Adds a verified boolean column to the twoFactor table that tracks whether a TOTP secret has been confirmed by the user.
enableTwoFactor creates the row with verified: false. The row is promoted to verified: true only after verifyTOTP succeeds with a valid code.enableTwoFactor when TOTP is already verified): the new row preserves verified: true, so the user is never locked out of sign-in while rotating their TOTP secret.verifyTOTP rejects rows where verified === false, preventing abandoned enrollments from blocking authentication. Backup codes and OTP are unaffected and work as fallbacks during unfinished enrollment.Migration: The new column defaults to true, so existing twoFactor rows are treated as verified. No data migration is required. skipVerificationOnEnable: true is also unaffected — the row is created as verified: true in that mode.
Updated dependencies []:
Fixed endpoint instrumentation to always use the route template
better-authINVALID_PASSWORD for all checkPassword failures (#8902)getSession accessibility in generic Auth<O> context (#9017)For detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@bytaesu, @jonathansamines, @ping-maxwell
Full changelog: v1.6.0...v1.6.1
#9023 2e537df Thanks @jonathansamines! - Update endpoint instrumentation to always use endpoint routes
#8902 f61ad1c Thanks @ping-maxwell! - use INVALID_PASSWORD for all checkPassword failures
#9017 7495830 Thanks @bytaesu! - restore getSession accessibility in generic Auth<O> context
Updated dependencies []:
Patched transitive node-forge vulnerability via samlify pin
Blog post: Better Auth 1.6
better-authfreshAge calculation with session creation time instead of update time (#8762)Migration:
session.freshAgenow calculates fromcreatedAt. Setsession: { freshAge: 0 }to disable the check entirely.
resendStrategy option to reuse existing OTP in email-otp plugin (#8560)enable option for HaveIBeenPwned plugin (#8728)sendMagicLink callback (#8571)secret option to OAuth proxy to reduce shared key exposure (#8699)organizationId parameter in team endpoints (#5062)twoFactorPage config option for custom 2FA page routing (#5329)oidc-provider plugin in favor of @better-auth/oauth-provider (#8985)accountId instead of internal id (#8786)skipOriginCheck array handling (#8582)user field through idToken sign-in body for Apple name support (#8417)operationId in admin plugin endpoints (#8570)sendOTP failures instead of silently swallowing them (#8842)cookieCache maxAge to match session.expiresIn (#8648)autoSignIn: false without requireEmailVerification (#8521)accountInfo endpoint to use accountId instead of internal id (#8346)createAdapter and type exports for backwards compatibility (#8461)Response return for HTTP request contexts (#7521)throw: true handling in client session refresh (#8610)generateId: "uuid" over adapter customIdGenerator (#8679)safeJSONParse for pre-parsed objects (#8248)CREATE INDEX (#8538)sessionSignal after requesting email change in email-otp (#8816)/magic-link/verify (#7223)form_post (#8895)storeIdentifier is hashed (#8980)redirect_uri validation for prompt=none in oidc-provider (#8398)listUserInvitations (#8694)twoFactorTable option to schema modelName (#8443)any from collapsing auth.$Infer and client inference types (#8981)updateUser to not overwrite unrelated username fields (#7570)updateUser (#8731)For detailed changes, see CHANGELOG
@better-auth/ssoMigration: Set
sso({ saml: { enableInResponseToValidation: false } })to restore the previous behavior.
node-forge vulnerability via samlify pin (#8838)sub claim correctly (#8276)provisionUser inconsistency and added provisionUserOnEveryLogin option (#8818)internalAdapter (#8353)For detailed changes, see CHANGELOG
@better-auth/mongo-adapterMigration: New documents use native BSON UUIDs. Existing string UUIDs continue to work. No data migration required.
For detailed changes, see CHANGELOG
@better-auth/oauth-providerisLocalhost function (#8286)customIdTokenClaims to override standard claims (#7865)baseURL config handling in init (#8649)oauth_query in client plugin (#8320)customIdTokenClaims to override acr and auth_time (#8633)auth_time timestamps across adapter shapes (#8761)skip_consent (#8632)prompt=none support (#8554)For detailed changes, see CHANGELOG
@better-auth/stripeprorationBehavior per plan (#8525)customerType check (#8609){CHECKOUT_SESSION_ID} placeholder in success callbackURL (#8568)priceId for annual subscriptions in list (#8810)For detailed changes, see CHANGELOG
@better-auth/drizzle-adaptermode: "insensitive") (#8556)IS NULL / IS NOT NULL for null value comparisons (#8660)For detailed changes, see CHANGELOG
@better-auth/exporequire issue (#8253)For detailed changes, see CHANGELOG
@better-auth/prisma-adapterupdateMany fallback for non-unique updates (#8524)deleteMany when deleting by non-unique field (#8314)For detailed changes, see CHANGELOG
authmcp.better-auth.com (#8747)required as true in Drizzle and Prisma generators (#8614)For detailed changes, see CHANGELOG
@better-auth/electronsafeStorage encryption failures gracefully (#8530)For detailed changes, see CHANGELOG
@better-auth/passkeyFor detailed changes, see CHANGELOG
@better-auth/test-utils@better-auth/test-utils/adapter (#8564)using keyword for runtime compatibility (#8756)For detailed changes, see CHANGELOG
@better-auth/api-keyFor detailed changes, see CHANGELOG
@better-auth/coreAPIErrors as span errors in OpenTelemetry traces (#8850)For detailed changes, see CHANGELOG
@better-auth/kysely-adapternumUpdatedOrDeletedRows from D1 dialect (#8798)For detailed changes, see CHANGELOG
@better-auth/telemetryFor detailed changes, see CHANGELOG
Thanks to everyone who contributed to this release:
@aarmful, @bytaesu, @dvanmali, @Eric-Song-Nop, @formatlos, @GautamBytes, @GoPro16, @gustavovalverde, @himself65, @jonathansamines, @jslno, @mrgrauel, @NathanColosimo, @okisdev, @olliethedev, @Oluwatobi-Mustapha, @OscarCornish, @ping-maxwell, @raihanbrillmark, @sicarius97, @Sigmabrogz, @wuzgood98, @xiaoyu2er, @YevheniiKotyrlo
Full changelog: v1.5.6...v1.6.0
#8836 5dd9e44 Thanks @gustavovalverde! - Add case-insensitive query support for database adapters
#8836 5dd9e44 Thanks @gustavovalverde! - Add optional version field to the plugin interface and expose version from all built-in plugins
#8985 dd537cb Thanks @gustavovalverde! - deprecate oidc-provider plugin in favor of @better-auth/oauth-provider
The oidc-provider plugin now emits a one-time runtime deprecation warning when instantiated and is marked as @deprecated in TypeScript. It will be removed in the next major version. Migrate to @better-auth/oauth-provider.
#8843 bd9bd58 Thanks @gustavovalverde! - enforce role-based authorization on SCIM management endpoints and normalize passkey ownership checks via shared authorization middleware
#8836 5dd9e44 Thanks @gustavovalverde! - Return additional user fields and session data from the magic-link verify endpoint
#8836 5dd9e44 Thanks @gustavovalverde! - Allow passwordless users to enable, disable, and manage two-factor authentication
#8836 5dd9e44 Thanks @gustavovalverde! - Prevent updateUser from overwriting unrelated username or displayUsername fields
#8836 5dd9e44 Thanks @gustavovalverde! - Use non-blocking scrypt for password hashing to avoid blocking the event loop
#8836 5dd9e44 Thanks @gustavovalverde! - Enforce username uniqueness when updating a user profile
#8836 5dd9e44 Thanks @gustavovalverde! - Align session fresh age calculation with creation time instead of update time
#8836 5dd9e44 Thanks @gustavovalverde! - Compare account cookie by provider accountId instead of internal id
#8836 5dd9e44 Thanks @gustavovalverde! - Trigger session signal after requesting email change in email-otp plugin
#8836 5dd9e44 Thanks @gustavovalverde! - Rethrow sendOTP failures in phone-number plugin instead of silently swallowing them
#8836 5dd9e44 Thanks @gustavovalverde! - Read OAuth proxy callback parameters from request body when using form_post response mode
#8980 469eee6 Thanks @bytaesu! - fix oauth state double-hashing when verification storeIdentifier is set to hashed
#8981 560230f Thanks @bytaesu! - Prevent any from collapsing auth.$Infer and auth.$ERROR_CODES. Preserve client query typing when body is any.
Updated dependencies [5dd9e44, 5dd9e44, 5dd9e44]:
`28b1291` Thanks @gustavovalverde! - Add case-insensitive query support for database adapters
28b1291 Thanks @gustavovalverde! - Add case-insensitive query support for database adapters
28b1291 Thanks @gustavovalverde! - Add optional version field to the plugin interface and expose version from all built-in plugins
28b1291 Thanks @gustavovalverde! - Return additional user fields and session data from the magic-link verify endpoint
28b1291 Thanks @gustavovalverde! - Allow passwordless users to enable, disable, and manage two-factor authentication
28b1291 Thanks @gustavovalverde! - Prevent updateUser from overwriting unrelated username or displayUsername fields
28b1291 Thanks @gustavovalverde! - Use non-blocking scrypt for password hashing to avoid blocking the event loop
28b1291 Thanks @gustavovalverde! - Enforce username uniqueness when updating a user profile
28b1291 Thanks @gustavovalverde! - Align session fresh age calculation with creation time instead of update time
28b1291 Thanks @gustavovalverde! - Compare account cookie by provider accountId instead of internal id
28b1291 Thanks @gustavovalverde! - Trigger session signal after requesting email change in email-otp plugin
28b1291 Thanks @gustavovalverde! - Rethrow sendOTP failures in phone-number plugin instead of silently swallowing them
28b1291 Thanks @gustavovalverde! - Read OAuth proxy callback parameters from request body when using form_post response mode
Updated dependencies [28b1291, 28b1291, 28b1291]:
*No significant changes* ##### View changes on GitHub
No significant changes
Agent auth plugin - by @Bekacru in https://github.com/better-auth/better-auth/issues/8696 (a0b53)
resendStrategy option to reuse existing OTP - by @bytaesu in https://github.com/better-auth/better-auth/issues/8560 <samp>(98c8e)</samp>organizationId in team endpoints - by @xiaoyu2er and @himself65 in https://github.com/better-auth/better-auth/issues/5062 <samp>(8f470)</samp>prorationBehavior per plan - by @bytaesu in https://github.com/better-auth/better-auth/issues/8525 <samp>(98cea)</samp>@better-auth/test-utils/adapter - by @bytaesu in https://github.com/better-auth/better-auth/issues/8564 <samp>(6be0f)</samp>twoFactorPage in config - by @wuzgood98 in https://github.com/better-auth/better-auth/issues/5329 <samp>(4f41b)</samp>skipOriginCheck array - by @jslno in https://github.com/better-auth/better-auth/issues/8582 <samp>(331c4)</samp>throw:true in session refresh - by @bytaesu in https://github.com/better-auth/better-auth/issues/8610 <samp>(275ca)</samp>{CHECKOUT_SESSION_ID} placeholder in success callbackURL - by @bytaesu in https://github.com/better-auth/better-auth/issues/8568 <samp>(32704)</samp>adapters: Restore deprecated createAdapter and type exports for backcompat - by @himself65 in https://github.com/better-auth/better-auth/issues/8461 (…
user field through idToken sign-in body for Apple name support - by @bytaesu and Copilot in https://github.com/better-auth/better-auth/issues/8417 <samp>(d364e)</samp>autoSignIn: false without requireEmailVerification - by @himself65 in https://github.com/better-auth/better-auth/issues/8521 <samp>(e3e66)</samp>CREATE INDEX for postgres migration - by @himself65 in https://github.com/better-auth/better-auth/issues/8538 <samp>(b9e54)</samp>Move adapter packages to dependencies to fix missing module errors - by @himself65 in https://github.com/better-auth/better-auth/issues/8401 (56857)
account: Use accountId instead of id in accountInfo endpoint - by @NathanColosimo and @himself65 in https://github.com/better-auth/better-auth/issues/
Access control indexing type - by @YevheniiKotyrlo and @himself65 in https://github.com/better-auth/better-auth/issues/8155 (5d7dd)
client: Use direct imports to fix bundler re-export type resolution - by @himself65 in https://github.com/better-auth/better-auth/issues/8261 (63bb7)
require - by @himself65 in https://github.com/better-auth/better-auth/issues/8253 <samp>(977bf)</samp>cookies: Use lookahead heuristic for splitting Set-Cookie headers - by @bytaesu in https://github.com/better-auth/better-auth/issues/8301 (add7b)
blog: Add draft support for blog posts and update image URLs - by @Bekacru (bbf34)
oauth-provider: Keep auth_time across id_token refresh - by @grant0417 in https://github.com/better-auth/better-auth/issues/8134 (c41d1)
upgrade command to update better-auth packages - by @himself65 in https://github.com/better-auth/better-auth/issues/8204 <samp>(00b54)</samp>require - by @himself65 in https://github.com/better-auth/better-auth/issues/8253 <samp>(35412)</samp>We recommend going through each breaking change to ensure a smooth upgrade.
We’re excited to announce the release of Better Auth 1.5! 🎉
This is our biggest release yet, with over 600 commits, 70 new features, 200 bug fixes, and 7 entirely new packages. From MCP authentication to Electron desktop support, this release brings Better Auth to new platforms and use cases.
We’re also announcing our new Infrastructure product. It lets you use a full user management and analytics dashboard, security and protection tooling, audit logs, a self-service SSO UI, and more, all with your own Better Auth instance.
Starting with this release, the self-service SSO dashboard — which lets your enterprise customers onboard their own SAML providers without support tickets — is powered by Better Auth Infrastructure. If you’re using the SSO plugin in production, we recommend upgrading to the Pro or Business tier to get access to the dashboard and streamline your enterprise onboarding.
And soon, you’ll be able to host your Better Auth instance on our infrastructure as well, so you can own your auth at scale without worrying about infrastructure needs.
Sign up now: https://better-auth.com/sign-in 🚀
To upgrade, run:
npx auth upgrade
We’re introducing a new standalone CLI: npx auth. This replaces the previous @better-auth/cli package, which will be deprecated in a future release.
npx auth init
With a single interactive command, npx auth init scaffolds a complete Better Auth setup — configuration file, database adapter, and framework integration.
All existing commands like migrate and generate are available through the new CLI as well:
npx auth migrate # Run database migrations
npx auth generate # Generate auth schema
npx auth upgrade # Upgrade Better Auth to the latest version
The generate command now also supports a --adapter flag, letting you generate schema output tailored to your specific database adapter without needing a full Better Auth config file:
npx auth generate --adapter prisma
npx auth generate --adapter drizzle
The MCP plugin now ships a framework-agnostic remote auth client. If your MCP server is separate from your Better Auth instance, you can verify tokens and protect resources without duplicating auth logic.
👉 Read more about MCP authentication
import { createMcpAuthClient } from "better-auth/plugins/mcp/client";
const mcpAuth = createMcpAuthClient({
authURL: "<https://my-app.com/api/auth>",
});
// Use as a handler wrapper
const handler = mcpAuth.handler(async (req, session) => {
// session contains userId, scopes, accessToken, clientId, etc.
return new Response("OK");
});
// Or verify tokens directly
const session = await mcpAuth.verifyToken(token);
It also comes with built-in framework adapters for Hono and Express-like servers:
import { mcpAuthHono } from "better-auth/plugins/mcp/client/adapters";
const middleware = mcpAuthHono(mcpAuth);
The new @better-auth/oauth-provider plugin turns your Better Auth instance into a full OAuth 2.1 authorization server with OIDC compatibility. Issue access tokens, manage client registrations, and let third-party apps authenticate against your API — including MCP agents.
👉 Read more about the OAuth Provider
import { betterAuth } from "better-auth";
import { jwt } from "better-auth/plugins";
import { oauthProvider } from "@better-auth/oauth-provider";
export const auth = betterAuth({
plugins: [
jwt(),
oauthProvider({
loginPage: "/sign-in",
consentPage: "/consent",
}),
],
});
Key features:
authorization_code, refresh_token, and client_credentials grants with openid scope support./jwks endpoint.Note:
The OAuth 2.1 Provider replaces the previous OIDC Provider plugin, which will be deprecated in a future release. The MCP plugin will also transition to use the OAuth 2.1 Provider as its foundation. See the migration guide for upgrading from the OIDC Provider plugin.
Full desktop authentication support for Electron apps. The plugin handles the complete OAuth flow — opening the system browser, exchanging authorization codes via custom protocol, and managing cookies securely.
👉 Read more about Electron integration
import { betterAuth } from "better-auth";
import { electron } from "@better-auth/electron";
export const auth = betterAuth({
plugins: [electron()],
});
import { createAuthClient } from "better-auth/client";
import { electronClient } from "@better-auth/electron/client";
const client = createAuthClient({
plugins: [
electronClient({
protocol: "com.example.myapp",
}),
],
});
// Opens system browser, handles callback, returns session
await client.requestAuth();
The new i18n plugin provides type-safe error message translations with automatic locale detection from headers, cookies, or sessions.
import { betterAuth } from "better-auth";
import { i18n } from "@better-auth/i18n";
export const auth = betterAuth({
plugins: [
i18n({
defaultLocale: "en",
detection: ["header", "cookie"],
translations: {
en: { USER_NOT_FOUND: "User not found" },
fr: { USER_NOT_FOUND: "Utilisateur non trouvé" },
es: { USER_NOT_FOUND: "Usuario no encontrado" },
},
}),
],
});
Error codes are fully typed — your IDE will autocomplete all available error codes from every registered plugin.
Every error response now includes a machine-readable code field. All first-party plugins define their own typed error codes using defineErrorCodes, and the APIError class supports them natively.
import { defineErrorCodes } from "@better-auth/core";
export const MY_ERROR_CODES = defineErrorCodes({
USER_NOT_FOUND: "User not found",
INVALID_TOKEN: "The provided token is invalid",
});
// In route handlers:
throw APIError.from("BAD_REQUEST", MY_ERROR_CODES.USER_NOT_FOUND);
Error responses now look like:
{
"code": "USER_NOT_FOUND",
"message": "User not found"
}
This is the foundation that the i18n plugin builds on — every error code from every plugin is discoverable at compile time, so translation dictionaries are fully type-checked.
The SSO plugin has received extensive hardening to be production-ready, with 23+ commits improving security and compliance.
As part of our new Infrastructure product, the SSO plugin is now accompanied by a self-service dashboard for onboarding enterprise customers. Organization admins can generate a shareable link that walks enterprise customers through configuring their SAML identity provider — no back-and-forth support tickets required.
The dashboard is available at:
https://better-auth.com/dashboard/[project]/organization/[orgId]/enterprise
From there, you can generate onboarding links, monitor SSO connection status, and manage provider configurations for each organization.
Full support for both SP-initiated and IdP-initiated SAML Single Logout:
import { betterAuth } from "better-auth";
import { sso } from "@better-auth/sso";
export const auth = betterAuth({
plugins: [
sso({
saml: {
enableSingleLogout: true, // [!code highlight]
wantLogoutRequestSigned: true,
wantLogoutResponseSigned: true,
},
}),
],
});
aud claim validation: Verify audience in OpenID Connect flows.Plugin hooks and global hooks now share the same AuthMiddleware type, making the hooks system consistent and composable across the entire auth pipeline.
import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";
export const auth = betterAuth({
hooks: {
before: createAuthMiddleware(async (ctx) => {
// Runs before every endpoint
console.log("Request to:", ctx.path);
}),
after: createAuthMiddleware(async (ctx) => {
// Runs after every endpoint, with access to the response
console.log("Response:", ctx.context.returned);
}),
},
});
Plugins use the same middleware type with matchers for targeted interception:
hooks: {
before: [{
matcher: (ctx) => ctx.path === "/sign-in/email",
handler: createAuthMiddleware(async (ctx) => { /* ... */ }),
}],
},
Better Auth can now resolve the base URL dynamically from incoming requests, making it work seamlessly with Vercel preview deployments, multi-domain setups, and reverse proxies.
👉 Read more about dynamic base URL
import { betterAuth } from "better-auth";
export const auth = betterAuth({
baseURL: {
allowedHosts: [
"myapp.com",
"*.vercel.app", // Any Vercel preview
"preview-*.myapp.com", // Pattern match
],
fallback: "<https://myapp.com>",
protocol: "auto",
},
});
Verification tokens can now be stored in secondary storage (e.g., Redis) instead of — or in addition to — the database. Identifiers can be hashed for extra security.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
secondaryStorage: {
// ... your Redis config
},
verification: {
storeIdentifier: "hashed", // Hash verification identifiers // [!code highlight]
storeInDatabase: false, // Only use secondary storage // [!code highlight]
},
});
You can also configure per-identifier overrides:
verification: {
storeIdentifier: {
default: "plain",
overrides: {
"email-verification": "hashed",
"password-reset": "hashed",
},
},
},
The rate limiter has been improved with separate request/response handling, hardened defaults, and IPv6 support.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
advanced: {
ipAddress: {
ipv6Subnet: 64, // Rate limit by /64 subnet
},
},
});
Better Auth now supports rotating BETTER_AUTH_SECRET without invalidating existing sessions, tokens, or encrypted data. When you need to rotate your secret — whether for scheduled rotation or incident response — you can introduce a new key while keeping old keys available for decryption.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
secrets: [
{ version: 2, value: "new-secret-key-at-least-32-chars" }, // current (first = active)
{ version: 1, value: "old-secret-key-still-used-to-decrypt" }, // previous
],
});
Or via environment variable:
BETTER_AUTH_SECRETS="2:new-secret-key,1:old-secret-key"
New data is always encrypted with the latest key (first in the array), while decryption automatically tries all configured keys. This lets you roll secrets gradually without downtime or data loss.
The Stripe plugin now supports per-seat billing for organizations. Member changes automatically sync seat quantity with Stripe.
import { betterAuth } from "better-auth";
import { stripe } from "@better-auth/stripe";
import { organization } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [
organization(),
stripe({
stripeClient,
stripeWebhookSecret: "whsec_...",
subscription: {
enabled: true,
plans: [
{
name: "team",
priceId: "price_base_monthly",
seatPriceId: "price_per_seat", // [!code highlight]
},
],
},
organization: { enabled: true }, // [!code highlight]
}),
],
});
The plugin also adds support for usage-based billing via lineItems, subscription schedules with scheduleAtPeriodEnd, and billingInterval tracking.
A new testUtils plugin provides factories, database helpers, and auth utilities for integration and E2E testing.
👉 Read more about test utilities
import { betterAuth } from "better-auth";
import { testUtils } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [testUtils({ captureOTP: true })],
});
const ctx = await auth.$context;
const test = ctx.test;
// Create and save a test user
const user = test.createUser({ email: "test@example.com" });
const savedUser = await test.saveUser(user);
// Login and get auth headers
const { headers, session, token } = await test.login({ userId: user.id });
// Capture OTPs for verification tests
const otp = test.getOTP("test@example.com");
A new /update-session endpoint allows updating custom additional session fields on the fly.
// Client-side
await authClient.updateSession({
theme: "dark",
language: "en",
});
This is useful when you have additional session fields that need to change without re-authentication.
Database adapters have been extracted into their own packages. This is a major architectural change that reduces bundle size and allows adapters to be versioned independently.
| Package | Description |
|---|---|
@better-auth/drizzle-adapter |
Drizzle ORM adapter |
@better-auth/prisma-adapter |
Prisma adapter |
@better-auth/kysely-adapter |
Kysely adapter |
@better-auth/mongo-adapter |
MongoDB adapter |
@better-auth/memory-adapter |
In-memory adapter |
The main better-auth package re-exports all adapters, so existing imports continue to work. But you can now install only the adapter you need for smaller bundles:
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { betterAuth } from "better-auth/minimal";
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "pg" }),
});
Better Auth now natively supports Cloudflare D1 as a first-class database option. Pass your D1 binding directly — no custom adapter setup required.
import { betterAuth } from "better-auth";
export default {
async fetch(request, env) {
const auth = betterAuth({
database: env.DB, // D1 binding, auto-detected // [!code highlight]
});
return auth.handler(request);
},
} satisfies ExportedHandler<{ DB: D1Database }>;
The built-in D1 dialect handles query execution, batch operations, and introspection through D1's native API. Note that D1 does not support interactive transactions — Better Auth uses D1's batch() API for atomicity instead.
verifyPassword API: New server-side endpoint to verify the current user's password.setShouldSkipSessionRefresh: Programmatically skip session refresh for specific requests.deferSessionRefresh: Support for read-replica database setups.customSyntheticUser option: Support plugin fields in enumeration-protected responses (#8097).VERCEL_URL and NEXTAUTH_URL: The client now falls back to VERCEL_URL and NEXTAUTH_URL environment variables when no explicit baseURL is configured, making server-side rendering on Vercel work out of the box.seatPriceId and lineItems enable flexible subscription checkouts, supporting modern pricing models like per-seat and usage-based billing.scheduleAtPeriodEnd: Defer plan changes to end of billing period.iss parameter: Authorization response issuer identifier.prompt=none support: Silent authentication for OIDC.magic-link: allowedAttempts option: Limit verification attempts.email-otp: Change email flow with OTP: Users can change their email address via OTP verification, with optional current-email confirmation for added security.email-otp: Name, image, and additional fields in sign-in: Richer OTP sign-in.phone-number: Additional fields in signUpOnVerification: Pass extra data.two-factor: twoFactorCookieMaxAge and server-side trust device expiration.one-tap: Button mode for Google sign-in.anonymous: Delete anonymous user endpoint.admin: Optional password on user creation.api-keys: Pagination for list endpoint, organization reference via metadata.organization: Function support for membershipLimit, reject expired invites.BetterAuthPluginRegistry type system: Typed plugin discovery via getPlugin() and hasPlugin().AuthContext: Access the Better Auth version at runtime.@better-auth/redis-storage./change-email: Always returns { status: true } and simulates token generation for timing safety (#8097).We recommend going through each breaking change to ensure a smooth upgrade.
The /forget-password/email-otp endpoint has been removed. Use the standard password reset flow instead.
The better-auth/adapters/test export has been removed. Use the testUtils plugin instead.
@better-auth/api-keyThe api-key plugin has been extracted into its own package. Install it separately:
npm install @better-auth/api-key
- import { apiKey } from "better-auth/plugins";
+ import { apiKey } from "@better-auth/api-key";
Schema changes:
userId field on the ApiKey table has been renamed to referenceId.configId field has been added (defaults to "default").Plugin options changes:
The permissions.defaultPermissions callback's first argument is now referenceId instead of userId:
export const auth = betterAuth({
plugins: [
apiKey({
permissions: {
- defaultPermissions: async (userId, ctx) => {
+ defaultPermissions: async (referenceId, ctx) => {
return {
files: ["read"],
users: ["read"],
};
},
}
})
]
})
Client SDK changes:
- const ownerId = apiKey.userId;
+ const ownerId = apiKey.referenceId;
+ const ownerType = apiKey.references; // "user" or "organization"
+ const configId = apiKey.configId;
If you are building a plugin on top of Better Auth, there are a few things you should know.
@deprecated APIs Are RemovedAll previously deprecated APIs have been removed. This includes deprecated adapter types, client types, helper types, and plugin options. If you were relying on any @deprecated methods or options, you'll need to migrate to their replacements:
| Removed | Replacement |
|---|---|
createAdapter |
createAdapterFactory |
Adapter |
DBAdapter |
TransactionAdapter |
DBTransactionAdapter |
Store (client) |
ClientStore |
AtomListener (client) |
ClientAtomListener |
ClientOptions |
BetterAuthClientOptions |
LiteralUnion, DeepPartial (from better-auth/types/helper) |
Import from @better-auth/core |
onEmailVerification |
afterEmailVerification |
sendChangeEmailVerification |
sendChangeEmailConfirmation |
advanced.database.useNumberId |
advanced.database.generateId: "serial" |
Organization permission field |
permissions (plural) |
@better-auth/core/utils Barrel Export RemovedThe @better-auth/core/utils barrel export has been split into individual subpath exports to improve tree-shaking:
- import { generateId, safeJSONParse, defineErrorCodes } from "@better-auth/core/utils";
+ import { generateId } from "@better-auth/core/utils/id";
+ import { safeJSONParse } from "@better-auth/core/utils/json";
+ import { defineErrorCodes } from "@better-auth/core/utils/error-codes";
$ERROR_CODES Type Changed to RawError ObjectsThe $ERROR_CODES field on plugins now expects Record<string, RawError> instead of Record<string, string>. Use defineErrorCodes() which now returns RawError objects with { code, message } instead of plain strings:
- $ERROR_CODES: {
- MY_ERROR: "My error message",
- },
+ $ERROR_CODES: defineErrorCodes({
+ MY_ERROR: "My error message",
+ }),
+ // Returns: { MY_ERROR: { code: "MY_ERROR", message: "My error message" } }
Use the new APIError.from() static method to throw errors with error codes:
import { APIError } from "@better-auth/core/error";
throw APIError.from("BAD_REQUEST", MY_ERROR_CODES.MY_ERROR);
PluginContext Is Now GenericPluginContext is now parameterized with Options:
type PluginContext<Options extends BetterAuthOptions> = {
getPlugin: <ID extends string>(pluginId: ID) => /* inferred from registry */ | null;
hasPlugin: <ID extends string>(pluginId: ID) => boolean; // narrows to `true` when plugin is registered
};
Plugins can register themselves via module augmentation for type-safe getPlugin() and hasPlugin():
declare module "@better-auth/core" {
interface BetterAuthPluginRegistry<AuthOptions, Options> {
"my-plugin": { creator: typeof myPlugin };
}
}
InferUser / InferSession Types RemovedThe InferUser<O> and InferSession<O> types have been removed. Use the generic User and Session types instead:
- import type { InferUser, InferSession } from "better-auth/types";
- type MyUser = InferUser<typeof auth>;
+ import type { User, Session } from "better-auth";
+ type MyUser = User<typeof auth.$options["user"], typeof auth.$options["plugins"]>;
Database "after" hooks (create.after, update.after, delete.after) now execute after the transaction commits, not during it. This prevents issues where hooks interacting with external systems (sending emails, calling APIs) could fail and roll back the entire transaction.
If your plugin relies on after hooks running inside the transaction for additional atomic database writes, you'll need to use the adapter directly within the main operation instead.
getMigrations Moved to better-auth/db/migration SubpathWe found that the getMigrations function includes many third-party dependencies, which caused some bundlers to unexpectedly include extra dependencies and increase output size. It's now available from a dedicated subpath:
- import { getMigrations } from "better-auth";
+ import { getMigrations } from "better-auth/db/migration";
id Field Removed from Session in Secondary StorageThe id field is used to determine relationships between structures in database models. We've removed it from secondary storage since it's not necessary there, simplifying the storage logic. If your plugin reads sessions from secondary storage and relies on the id field, you'll need to update your code accordingly.
init() Context Is Now MutableThe context object passed to a plugin's init() callback is now the same reference used throughout the auth lifecycle. init() can also return arbitrary keys via Record<string, unknown>, enabling plugins to inject custom context values that other plugins can access.
This release includes over 220 bug fixes addressing issues across all areas:
refresh_token_expires_in handling, callback routing, and token encryption.updateSession changes and removed duplicate writes.A lot of refinements to make everything smoother, faster, and more reliable. 👉 Check the full changelog
Thanks to all the contributors for making this release possible!
Remove max validation on siwe verify endpoint - by @orshih6 and @himself65 in https://github.com/better-auth/better-auth/issues/8158 (84565)
getAccountCookie from better-auth/cookies - by @bytaesu in https://github.com/better-auth/better-auth/issues/8181 <samp>(6beb0)</samp>/docs/errors routes to /docs/reference/errors - by @bytaesu in https://github.com/better-auth/better-auth/issues/8160 <samp>(e8a84)</samp>api-key: Organization support in API-Keys & Multiple config support - by @ping-maxwell and @himself65 in https://github.com/better-auth/better-auth/is
$ERROR_CODES - by @marcellosso in https://github.com/better-auth/better-auth/issues/8136 <samp>(a187e)</samp>expo-web-browser is not installed as a dependency - by @AdiMarianMutu and @himself65 in https://github.com/better-auth/better-auth/issues/7752 <samp>(5fc09)</samp>Drizzle transform input crashes dates - by @ping-maxwell in https://github.com/better-auth/better-auth/issues/8105 (2e1c1)
Limit enumeration on sign-up when email verification is required - by @bytaesu in https://github.com/better-auth/better-auth/issues/8091 (3ec7d)
/update-session - by @himself65 and @ping-maxwell in https://github.com/better-auth/better-auth/issues/8084 <samp>(f2124)</samp>scheduleAtPeriodEnd option to defer plan changes - by @bytaesu in https://github.com/better-auth/better-auth/issues/8064 <samp>(51808)</samp>user in hooks - by @jslno in https://github.com/better-auth/better-auth/issues/8026 <samp>(62ed6)</samp>Support accepting callback for trusted providers function - by @Siumauricio and @Paola3stefania in https://github.com/better-auth/better-auth/issues/7
sanitizeUser option - by @jslno in https://github.com/better-auth/better-auth/issues/7976 <samp>(7306c)</samp>required attr properly - by @jslno in https://github.com/better-auth/better-auth/issues/7996 <samp>(cec49)</samp>url instead of uri in continue and consent endpoints - by @bytaesu in https://github.com/better-auth/better-auth/issues/7811 <samp>(88e1e)</samp>stripeCustomerId on /subscription/cancel/callback endpoint - by @bytaesu in https://github.com/better-auth/better-auth/issues/8032 <samp>(76d9b)</samp>Encode callbackURL in delete-user verification email - by @Paola3stefania in https://github.com/better-auth/better-auth/issues/8007 (a2f6f)
getSessionCookie - by @jslno in https://github.com/better-auth/better-auth/issues/8008 <samp>(99efd)</samp>i18n: Allow getLocale callback when request is undefined - by @bytaesu in https://github.com/better-auth/better-auth/issues/7834 (72491)
getLocale callback when request is undefined - by @bytaesu in https://github.com/better-auth/better-auth/issues/7834 <samp>(72491)</samp>Make name field optional " - by @himself65 in https://github.com/better-auth/better-auth/issues/7617 (00c95)
name field optional " - by @himself65 in https://github.com/better-auth/better-auth/issues/7617 <samp>(00c95)</samp>getCurrentAdapter for user lookup to avoid transaction deadlock - by @sakamoto-wk in https://github.com/better-auth/better-auth/issues/7758 <samp>(7db4e)</samp>.env.local to dotenv - by @himself65 in https://github.com/better-auth/better-auth/issues/7831 <samp>(3b2b9)</samp>verifyIdToken support for Microsoft Entra ID provider - by @bytaesu in https://github.com/better-auth/better-auth/issues/7795 <samp>(75585)</samp>deleteVerificationByIdentifier for secondary-storage cleanup - by @bytaesu in https://github.com/better-auth/better-auth/issues/7790 <samp>(d1b82)</samp>Make name field optional - by @bytaesu in https://github.com/better-auth/better-auth/issues/7617 (e0df7)
name field optional - by @bytaesu in https://github.com/better-auth/better-auth/issues/7617 <samp>(e0df7)</samp>select support - by @jslno in https://github.com/better-auth/better-auth/issues/7667 <samp>(20d08)</samp>signUpOnVerification flow - by @bytaesu and @himself65 in https://github.com/better-auth/better-auth/issues/7699 <samp>(9e1ab)</samp>newRole - by @jslno in https://github.com/better-auth/better-auth/issues/7687 <samp>(230cb)</samp>never[] to UserWithRole[] - by @LovelessCodes in https://github.com/better-auth/better-auth/issues/7701 <samp>(b00bc)</samp>better-call peerDeps - by @bytaesu in https://github.com/better-auth/better-auth/issues/7676 <samp>(bcdcd)</samp>better-call peerDeps - by @bytaesu in https://github.com/better-auth/better-auth/issues/7675 <samp>(f5d56)</samp>Mark /forget-password/email-otp as deprecation - by @bytaesu in https://github.com/better-auth/better-auth/issues/7645 (97e6d)
setShouldSkipSessionRefresh - by @himself65 in https://github.com/better-auth/better-auth/issues/7625 <samp>(ac81f)</samp>disableImplicitLinking to accountLinking - by @Paola3stefania and @himself65 in https://github.com/better-auth/better-auth/issues/7270 <samp>(f11cd)</samp>/forget-password/email-otp as deprecation - by @bytaesu in https://github.com/better-auth/better-auth/issues/7645 <samp>(97e6d)</samp>deferSessionRefresh option to support read-replica setups - by @Paola3stefania, Alexander Asomba, Bereket Engida and @himself65 in https://github.com/better-auth/better-auth/issues/6871 <samp>(36f55)</samp>account_data cookie when session is refreshed - by @bytaesu and @himself65 in https://github.com/better-auth/better-auth/issues/7576 <samp>(96a7e)</samp>sendOnSignUp option - by @bytaesu in https://github.com/better-auth/better-auth/issues/7593 <samp>(762a1)</samp>returned: false fields from API responses - by @Paola3stefania and @himself65 in https://github.com/better-auth/better-auth/issues/7531 <samp>(87777)</samp>admin: Make password field optional on create user - by @Bekacru and @cursoragent in https://github.com/better-auth/better-auth/issues/7441 (c11ac)
/minimal includes unexpected deps - by @himself65 in https://github.com/better-auth/better-auth/issues/7467 <samp>(1668a)</samp>Set-Cookie when APIError thrown in hooks - by @himself65 in https://github.com/better-auth/better-auth/issues/7478 <samp>(a5f42)</samp>baseURL is not set - by @bytaesu in https://github.com/better-auth/better-auth/issues/7159 <samp>(46c9f)</samp>returned: false fields from output schemas - by @Paola3stefania in https://github.com/better-auth/better-auth/issues/7504 <samp>(5cc0a)</samp>activeTeamId field when dynamic access control is enabled - by @longnguyen2004, @himself65, ping-maxwell and @ping-maxwell in https://github.com/better-auth/better-auth/issues/7385 <samp>(00bda)</samp>Add skipTrailingSlashes option to advanced config - by @bytaesu in https://github.com/better-auth/better-auth/issues/7404 (fd1dc)
skipTrailingSlashes option to advanced config - by @bytaesu in https://github.com/better-auth/better-auth/issues/7404 <samp>(fd1dc)</samp>locale option to upgradeSubscription - by @bytaesu in https://github.com/better-auth/better-auth/issues/7421 <samp>(2fe46)</samp>core: Add version in AuthContext - by @himself65 in https://github.com/better-auth/better-auth/issues/7362 (d9021)
AuthContext - by @himself65 in https://github.com/better-auth/better-auth/issues/7362 <samp>(d9021)</samp>refetch to useSession for all clients - by @Paola3stefania in https://github.com/better-auth/better-auth/issues/7255 <samp>(249c0)</samp>getSchema for proper field inference - by @bytaesu in https://github.com/better-auth/better-auth/issues/7353 <samp>(e0230)</samp>core: Remove dual module warning - by @himself65 in https://github.com/better-auth/better-auth/issues/7308 (38ab0)
oauth: Add custom authorizationEndpoint option - by @bytaesu and Copilot in https://github.com/better-auth/better-auth/issues/6962 (69c9c)
organization: Add function support to membershipLimit option in organization plugin - by @amrnt and @ping-maxwell in https://github.com/better-auth/be
Add auth.api.verifyPassword - by @SaviruFr and @himself65 in https://github.com/better-auth/better-auth/issues/6934 (9dae1)
auth.api.verifyPassword - by @SaviruFr and @himself65 in https://github.com/better-auth/better-auth/issues/6934 <samp>(9dae1)</samp>Gumroad login support - by @ptaberg and @himself65 in https://github.com/better-auth/better-auth/issues/7100 <samp>(fd5af)</samp>change-email-verification flow - by @bytaesu in https://github.com/better-auth/better-auth/issues/7160 <samp>(502a6)</samp>verifyApiKey - by @GautamBytes and @ping-maxwell in https://github.com/better-auth/better-auth/issues/6259 <samp>(76a41)</samp>updateAccountOnSignIn is false - by @bytaesu in https://github.com/better-auth/better-auth/issues/7217 <samp>(cd2ea)</samp>ZodDefault fields - by @MuzzaiyyanHussain and Taesu in https://github.com/better-auth/better-auth/issues/7150 <samp>(d727c)</samp>subscriptionSuccess route - by @bytaesu in https://github.com/better-auth/better-auth/issues/7087 <samp>(a4200)</samp>Support form data for email sign-in/sign-up and fallback to checking fetch Metadata for first login - by @Paola3stefania, @bytaesu, Bereket Engida and
webBrowserOptions to openAuthSessionAsync - by @himself65 and Copilot in https://github.com/better-auth/better-auth/issues/7054 <samp>(76d94)</samp>customer.subscription.created webhook event - by @bytaesu, Copilot and @himself65 in https://github.com/better-auth/better-auth/issues/6924 <samp>(bb894)</samp>disableRedirect option for subscription and billing - by @himself65 and Valerii Strilets in https://github.com/better-auth/better-auth/issues/7068 <samp>(5cc56)</samp>accountLinking default to true - by @bytaesu and @himself65 in https://github.com/better-auth/better-auth/issues/6963 <samp>(4f1ec)</samp>updateSession changes to secondary storage and active-sessions list - by @Ridhim-RR, @bytaesu and Taesu in https://github.com/better-auth/better-auth/issues/6988 <samp>(bea45)</samp>/has-permission - by @himself65 and Copilot in https://github.com/better-auth/better-auth/issues/7016 <samp>(50990)</samp>onRequest hooks properly - by @bytaesu in https://github.com/better-auth/better-auth/issues/7070 <samp>(2bc13)</samp>parseSetCookieHeader - by @bytaesu in https://github.com/better-auth/better-auth/issues/6990 <samp>(1b329)</samp>data.id instead of challengeId in deleteVerificationValue - by @GautamBytes in https://github.com/better-auth/better-auth/issues/6826 <samp>(bd5ca)</samp>saml: Reject deprecated SAML signature and digest algorithms - by @Paola3stefania in https://github.com/better-auth/better-auth/issues/6784 (1f171)
trustedOrigins - by @bytaesu in https://github.com/better-auth/better-auth/issues/6904 <samp>(ae90b)</samp>info --json unexpected exit with 1 - by @himself65 in https://github.com/better-auth/better-auth/issues/6949 <samp>(54712)</samp>cli: Warn when old @better-auth/cli is used with better-auth v1.5.x+ - by @himself65 (73ca9)
Update workspace dependency ranges to workspace:* - by @himself65 (4e7cf)
workspace:* - by @himself65 <samp>(4e7cf)</samp>cookie: Add deprecated options alias for backward compatibility - by @himself65 in https://github.com/better-auth/better-auth/issues/8139 (07447)
options alias for backward compatibility - by @himself65 in https://github.com/better-auth/better-auth/issues/8139 <samp>(07447)</samp>Improve select support - by @jslno in https://github.com/better-auth/better-auth/issues/7667 (4aae0)
select support - by @jslno in https://github.com/better-auth/better-auth/issues/7667 <samp>(4aae0)</samp>signUpOnVerification flow - by @bytaesu and @himself65 in https://github.com/better-auth/better-auth/issues/7699 <samp>(f3080)</samp>newRole - by @jslno in https://github.com/better-auth/better-auth/issues/7687 <samp>(9312d)</samp>getCurrentAdapter for user lookup to avoid transaction deadlock - by @sakamoto-wk in https://github.com/better-auth/better-auth/issues/7758 <samp>(327ee)</samp>never[] to UserWithRole[] - by @LovelessCodes in https://github.com/better-auth/better-auth/issues/7701 <samp>(3c0c5)</samp>user in hooks - by @jslno in https://github.com/better-auth/better-auth/issues/8026 <samp>(17407)</samp>.env.local to dotenv - by @himself65 in https://github.com/better-auth/better-auth/issues/7831 <samp>(e804e)</samp>getSessionCookie - by @jslno in https://github.com/better-auth/better-auth/issues/8008 <samp>(81f50)</samp>required attr properly - by @jslno in https://github.com/better-auth/better-auth/issues/7996 <samp>(c44a8)</samp>verifyIdToken support for Microsoft Entra ID provider - by @bytaesu in https://github.com/better-auth/better-auth/issues/7795 <samp>(80120)</samp>url instead of uri in continue and consent endpoints - by @bytaesu in https://github.com/better-auth/better-auth/issues/7811 <samp>(fb56f)</samp>acceptInvitation - by @Saurav3004, Taesu and @himself65 in https://github.com/better-auth/better-auth/issues/7825 <samp>(3f254)</samp>deleteVerificationByIdentifier for secondary-storage cleanup - by @bytaesu in https://github.com/better-auth/better-auth/issues/7790 <samp>(6efdc)</samp>better-call peerDeps - by @bytaesu in https://github.com/better-auth/better-auth/issues/7676 <samp>(d323b)</samp>better-call peerDeps - by @bytaesu in https://github.com/better-auth/better-auth/issues/7675 <samp>(f63bf)</samp>stripeCustomerId on /subscription/cancel/callback endpoint - by @bytaesu in https://github.com/better-auth/better-auth/issues/8032 <samp>(15519)</samp>Mark /forget-password/email-otp as deprecation - by @bytaesu in https://github.com/better-auth/better-auth/issues/7645 (8f333)
disableImplicitLinking to accountLinking - by @Paola3stefania and @himself65 in https://github.com/better-auth/better-auth/issues/7270 <samp>(a7740)</samp>/forget-password/email-otp as deprecation - by @bytaesu in https://github.com/better-auth/better-auth/issues/7645 <samp>(8f333)</samp>account_data cookie when session is refreshed - by @bytaesu and @himself65 in https://github.com/better-auth/better-auth/issues/7576 <samp>(5d3f7)</samp>sendOnSignUp option - by @bytaesu in https://github.com/better-auth/better-auth/issues/7593 <samp>(33619)</samp>returned: false fields from API responses - by @Paola3stefania and @himself65 in https://github.com/better-auth/better-auth/issues/7531 <samp>(57f1e)</samp>two-factor: Add twoFactorCookieMaxAge as a separate option - by @Bekacru (c6e4f)
baseURL is not set - by @bytaesu in https://github.com/better-auth/better-auth/issues/7159 <samp>(f7cbb)</samp>returned: false fields from output schemas - by @Paola3stefania in https://github.com/better-auth/better-auth/issues/7504 <samp>(86db4)</samp>admin: Make password field optional on create user - by @Bekacru and @cursoragent in https://github.com/better-auth/better-auth/issues/7441 (01bd8)
updateAccountOnSignIn is false - by @bytaesu in https://github.com/better-auth/better-auth/issues/7217 <samp>(56bc0)</samp>activeTeamId field when dynamic access control is enabled - by @longnguyen2004, @himself65, ping-maxwell and @ping-maxwell in https://github.com/better-auth/better-auth/issues/7385 <samp>(b7ff1)</samp>One column per month.