Convex + Better Auth

Upgrading from 0.10

Upgrade @convex-dev/better-auth from 0.10 to the latest version

Work through these steps in order, then deploy once. If you use Local Install and your database already has organization teams, you need a second deploy, described in Regenerate schema.

Dependencies

Install dependencies

Install the latest component and Better Auth 1.7.16 or a later 1.7.x release, even if you're several releases behind. You don't need to install anything in between.

npm install @convex-dev/better-auth@^0.13.0
npm install better-auth@~1.7.16

Review the breaking changes in each Better Auth release between your version and 1.7: 1.4, 1.5, 1.6, and the 1.7 upgrade guide.

Upgrade any other Better Auth packages in your dependencies, such as @better-auth/expo, to the same version.

Auth config

Set baseURL for client-side frameworks

If your app uses the cross-domain plugin (e.g., Vite SPA, Expo Web), add baseURL to your betterAuth() options so Better Auth doesn't infer it from each request.

convex/auth.ts
betterAuth({
  baseURL: process.env.CONVEX_SITE_URL, 
  // ...
});

Next.js and TanStack Start setups already set baseURL and are not affected.

Dynamic baseURL and forwarded headers

This step applies only to apps with a dynamic baseURL.

Better Auth 1.7 ignores x-forwarded-host and x-forwarded-proto unless advanced.trustedProxyHeaders is set. You don't need to set it: the component sets the request URL and host header itself, and Better Auth 1.7 reads them instead. The Next.js and TanStack Start handlers need no changes.

If you run your own proxy in front of .convex.site, the component replaces any x-forwarded-host and x-forwarded-proto your proxy sends, whether or not trustedProxyHeaders is set. Send your public origin in x-better-auth-forwarded-host and x-better-auth-forwarded-proto instead, and list it exactly, without wildcards, in trustedOrigins or allowedHosts.

Generic OAuth callback path

This step applies only to apps that use the genericOAuth() plugin.

Better Auth 1.7 moved Generic OAuth callbacks from /api/auth/oauth2/callback/<providerId> to the standard social path, /api/auth/callback/<providerId>. Change the redirect URI registered with each provider, and any redirectURI in a provider config, to the new path.

redirectURI: `${siteUrl}/api/auth/oauth2/callback/slack`, 
redirectURI: `${siteUrl}/api/auth/callback/slack`, 

Remove generateId: "uuid"

Remove advanced.database.generateId: "uuid" from your Better Auth options. It never had an effect, because Convex assigns document ids, and on Better Auth 1.7 it turns off enforcement of verification reservations, the single-use locks Better Auth takes on verification values. The Convex plugin logs a warning while it is set.

Plugins

Passkey plugin removed

The component no longer bundles the passkey plugin or has the passkey table in its schema. If you use passkeys, switch to Local Install and install @better-auth/passkey directly.

Client

Generic OAuth sign-in moved to signIn.social

Better Auth 1.7 removed authClient.signIn.oauth2(), authClient.oauth2.link() and the genericOAuthClient() plugin, so remove the plugin from your auth client. Sign in to Generic OAuth providers with authClient.signIn.social() and link them with authClient.linkSocial(), passing the providerId from your genericOAuth() config as provider.

auth-client.ts
import { genericOAuthClient } from "better-auth/client/plugins"; 

export const authClient = createAuthClient({
  plugins: [
    genericOAuthClient(), 
    convexClient(),
  ],
});
await authClient.signIn.oauth2({ providerId: "slack" }); 
await authClient.signIn.social({ provider: "slack" }); 
await authClient.oauth2.link({ providerId: "slack" }); 
await authClient.linkSocial({ provider: "slack" }); 

twoFactor.enable() returns a discriminated union

If your app uses the two-factor plugin, authClient.twoFactor.enable() now returns { method: "otp" } or { method: "totp", totpURI, backupCodes }. Check method before reading totpURI.

const { data } = await authClient.twoFactor.enable({ password });
if (data?.totpURI) { 
if (data?.method === "totp") { 
  setTotpUri(data.totpURI);
}

Sorting on a field without an index fails

A list sorted on a field that no index covers now fails with an error. When an index could serve the sort, the error lists its fields. Before 0.13, these lists came back in creation order instead of the requested order. This affects lists where the caller picks the sort field, such as the admin plugin's listUsers sorted by role (or by name while filtering by role) and the organization plugin's listMembers sorted by role. Lists sorted by an indexed field, including user lists sorted by createdAt, email or name, work as before. Sorting by id isn't supported.

With Local Install, you can add the index the error describes.

Convex plugin

Plugin endpoint keys renamed

The Convex plugin's getToken, getJwks and getOpenIdConfig endpoints are renamed to getConvexToken, getConvexJwks and getConvexOpenIdConfig. Better Auth merges plugin endpoints by key, so another plugin with the same endpoint names, such as jwt, could replace them. The HTTP paths (/convex/token, /convex/jwks, /convex/.well-known/openid-configuration) and authClient.convex.token() are unchanged. If your server code calls auth.api.getToken(), auth.api.getJwks() or auth.api.getOpenIdConfig() expecting the Convex plugin's endpoints, switch to auth.api.getConvexToken(), auth.api.getConvexJwks() or auth.api.getConvexOpenIdConfig().

The cross-domain plugin's verifyOneTimeToken endpoint is renamed verifyCrossDomainOneTimeToken for the same reason; /cross-domain/one-time-token/verify and authClient.crossDomain.oneTimeToken.verify() are unchanged.

oidcProvider is no longer supported

Better Auth 1.7 removed the oidcProvider plugin, which the Convex plugin used internally to serve its OpenID discovery document. The component now serves the document itself, and its schema no longer declares the three tables oidcProvider added: oauthApplication, oauthAccessToken and oauthConsent.

The document now lists only the issuer, the JWKS URI and the token capabilities that Convex and other relying parties need. Before, it also listed /oauth2/* authorization, token, userinfo, registration and end-session endpoints, which the Convex plugin never served.

Apps can no longer act as an OpenID provider by adding the oidcProvider plugin themselves. Better Auth 1.7 requires compound unique indexes for it, and the Convex adapter doesn't support them: schema generation and the adapter throw an error on any plugin that declares them.

Upgrading deletes nothing. Convex keeps an undeclared table and its documents, and stops validating them. In most apps these tables are empty, because the component never wrote to them, and you can delete them from the component in the Convex dashboard. If your app was an OpenID provider, oauthApplication holds your registered clients, including client secrets and redirect URLs; export it before you delete anything.

Local Install

These steps apply only to apps that use Local Install.

Export the new adapter functions

Better Auth 1.7 adds two atomic adapter operations, consumeOne and incrementOne, which the component implements as Convex mutations. Export them from your adapter file alongside the existing functions.

convex/betterAuth/adapter.ts
export const {
  create,
  findOne,
  findMany,
  updateOne,
  updateMany,
  deleteOne,
  deleteMany,
  consumeOne, 
  incrementOne, 
} = createApi(schema, createAuthOptions);

Regenerate schema

With Local Install, regenerate the schema whenever you update Better Auth. Version 1.7 adds fields that Convex can write only after the schema declares them: failedVerificationCount and lockedUntil on twoFactor, alg and crv on jwks, and, for the organization plugin, memberCount on team and membershipKey on teamMember. It also adds an accountId_providerId_userId index on account, which Better Auth reads when a user sets, changes or resets a password. Without the index, each of those operations scans the whole table.

Run the Better Auth CLI as npx auth@1.7 generate, which replaces the older npx @better-auth/cli generate command. Keep the CLI on the same minor version as better-auth; a newer CLI generates the schema for its own Better Auth version. The CLI needs Node.js 22.12 or later.

cd convex/betterAuth
npx auth@1.7 generate

If your options include the oidcProvider plugin, remove it before you generate the schema, because Better Auth 1.7 no longer has it.

If your database already has organization teams, Convex rejects the deploy: the generated schema requires team.memberCount, and existing teams don't have it. First, make memberCount optional and deploy:

convex/betterAuth/schema.ts
team: defineTable({
  name: v.string(),
  memberCount: v.number(), 
  memberCount: v.optional(v.number()), 
  // ...
});

Then set memberCount on each team from its members. This mutation updates 100 teams per transaction and schedules itself for the next batch:

convex/betterAuth/migrations.ts
import { v } from "convex/values";
import { internal } from "./_generated/api";
import { internalMutation } from "./_generated/server";

export const backfillTeamMemberCount = internalMutation({
  args: { cursor: v.optional(v.union(v.string(), v.null())) },
  handler: async (ctx, args) => {
    const { page, isDone, continueCursor } = await ctx.db
      .query("team")
      .paginate({ numItems: 100, cursor: args.cursor ?? null });
    for (const team of page) {
      if (team.memberCount !== undefined) {
        continue;
      }
      const members = await ctx.db
        .query("teamMember")
        .withIndex("teamId", (q) => q.eq("teamId", team._id))
        .collect();
      await ctx.db.patch("team", team._id, { memberCount: members.length });
    }
    if (!isDone) {
      await ctx.scheduler.runAfter(
        0,
        internal.migrations.backfillTeamMemberCount,
        { cursor: continueCursor }
      );
    }
  },
});
npx convex run --component betterAuth migrations:backfillTeamMemberCount

The command returns after the first batch, and later batches run in the background. Each batch reads every member of its teams, so lower numItems if teams have thousands of members, to stay within Convex's transaction limits. Until the backfill finishes, teams without memberCount reject new members if a team member limit is set. Then regenerate the schema so memberCount is required again, and deploy.

On this page