Convex + Better Auth

Upgrading from 0.9

Upgrade @convex-dev/better-auth from 0.9 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

Use customJwt auth config

Use customJwt auth config, which validates JWTs faster. getAuthConfigProvider() generates the provider config.

convex/auth.config.ts
import type { AuthConfig } from "convex/server";
import { getAuthConfigProvider } from "@convex-dev/better-auth/auth-config";

export default {
  providers: [
    getAuthConfigProvider(), 
    {
      applicationID: "convex",
      domain: process.env.CONVEX_SITE_URL!,
    },
  ],
} satisfies AuthConfig;

Update Convex Better Auth plugin config

Pass your auth config object to the convex() plugin, which now requires it.

With customJwt auth config, the plugin signs tokens with RS256 instead of EdDSA, so existing signing keys don't match. Set jwksRotateOnTokenGenerationError to true so the plugin rotates them when token generation fails. You can remove it after the rotation.

convex/auth.ts
import authConfig from "./auth.config";

export const createAuth = (ctx: GenericCtx<DataModel>) => {
  return betterAuth({
    baseURL: siteUrl,
    database: authComponent.adapter(ctx),
    // ... other auth config
    plugins: [
      // ... other plugins
      convex(), 
      convex({
        authConfig,
        jwksRotateOnTokenGenerationError: true,
      }),
    ],
  });
};

Drop optionsOnly parameter from createAuth

Remove the optionsOnly parameter from createAuth, along with the logger option that reads it.

convex/auth.ts
export const createAuth = (
  ctx: GenericCtx<DataModel>,
  { optionsOnly } = { optionsOnly: false },
) => {
export const createAuth = (ctx: GenericCtx<DataModel>) => { 
  return betterAuth({
    logger: {
      disabled: optionsOnly,
    },
    // ... 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.

Server rendering

These steps apply only to apps that use server-side rendering, such as Next.js and TanStack Start apps.

Update framework server utilities

The component provides Next.js and TanStack Start utilities that manage auth on the server, as the client does. The configuration takes explicit Convex URLs and validates them at runtime.

Replace the old functions with their new versions, such as preloadQuery with preloadAuthQuery and fetchQuery with fetchAuthQuery. The new versions take only a function reference and arguments, and no third options argument such as a token.

lib/auth-server.ts
import { createAuth } from "@/convex/auth"; 
import { getToken as getTokenNextjs } from "@convex-dev/better-auth/nextjs"; 
import { convexBetterAuthNextJs } from "@convex-dev/better-auth/nextjs"; 

export const getToken = () => {
  return getTokenNextjs(createAuth);
};

export const {
  handler,
  preloadAuthQuery,
  isAuthenticated,
  getToken,
  fetchAuthQuery,
  fetchAuthMutation,
  fetchAuthAction,
} = convexBetterAuthNextJs({
  convexUrl: process.env.NEXT_PUBLIC_CONVEX_URL!,
  convexSiteUrl: process.env.NEXT_PUBLIC_CONVEX_SITE_URL!,
});
src/lib/auth-server.ts
import { createAuth } from "convex/auth";
import { setupFetchClient } from "@convex-dev/better-auth/react-start";
import { getCookie } from "@tanstack/react-start/server";
import { convexBetterAuthReactStart } from "@convex-dev/better-auth/react-start"; 

export const { fetchQuery, fetchMutation, fetchAction } =
  await setupFetchClient(createAuth, getCookie);

export const {
  handler,
  getToken,
  fetchAuthQuery,
  fetchAuthMutation,
  fetchAuthAction,
} = convexBetterAuthReactStart({
  convexUrl: process.env.VITE_CONVEX_URL!,
  convexSiteUrl: process.env.VITE_CONVEX_SITE_URL!,
});

Update route handlers

Change your route handlers to use the handler from your auth server file.

app/api/auth/[...all]/route.ts
import { nextJsHandler } from "@convex-dev/better-auth/nextjs"; 
import { handler } from "@/lib/auth-server"; 

export const { GET, POST } = nextJsHandler(); 
export const { GET, POST } = handler; 
src/routes/api/auth/$.ts
import { createFileRoute } from '@tanstack/react-router'
import { reactStartHandler } from '@convex-dev/better-auth/react-start'
import { handler } from '~/lib/auth-server'

export const Route = createFileRoute('/api/auth/$')({
  server: {
    handlers: {
      GET: ({ request }) => reactStartHandler(request),
      POST: ({ request }) => reactStartHandler(request),
      GET: ({ request }) => handler(request),
      POST: ({ request }) => handler(request),
    },
  },
})

Pass initial token to ConvexBetterAuthProvider

In Next.js and TanStack Start apps, pass an initial token to ConvexBetterAuthProvider so the client authenticates faster.

Update your ConvexClientProvider to accept it.

app/ConvexClientProvider.tsx
export function ConvexClientProvider({
  children,
  initialToken, 
}: {
  children: ReactNode;
  initialToken?: string | null; 
}) {
  return (
    <ConvexBetterAuthProvider
      client={convex}
      authClient={authClient}
      initialToken={initialToken} 
    >
      {children}
    </ConvexBetterAuthProvider>
  );
}

Then get the token on the server in your root layout and pass it to ConvexClientProvider.

app/layout.tsx
import { getToken } from "@/lib/auth-server"; 
import { ConvexClientProvider } from "./ConvexClientProvider";
import { PropsWithChildren } from "react";

export default async function RootLayout({ children }: PropsWithChildren) {
  const token = await getToken(); 
  return (
    <html>
      <body>
        <ConvexClientProvider>
        <ConvexClientProvider initialToken={token}>
          {children}
        </ConvexClientProvider>
      </body>
    </html>
  );
}
src/routes/__root.tsx
function RootComponent() {
  const context = useRouteContext({ from: Route.id })
  return (
    <ConvexBetterAuthProvider
      client={context.convexQueryClient.convexClient}
      authClient={authClient}
      initialToken={context.token} 
    >
      <RootDocument>
        <Outlet />
      </RootDocument>
    </ConvexBetterAuthProvider>
  )
}

Next.js

Use usePreloadedAuthQuery

Replace usePreloadedQuery with usePreloadedAuthQuery, which takes the same arguments and keeps showing the server-rendered data until authentication is ready.

app/(auth)/(dashboard)/todo-list.tsx
import { usePreloadedAuthQuery } from "@convex-dev/better-auth/nextjs/client";

export const TodoList = ({ preloadedUserQuery }) => {
  const userQuery = usePreloadedAuthQuery(preloadedUserQuery);
  return (
    <div>
      <h1>{userQuery?.name}</h1>
    </div>
  );
};

TanStack Start

Update Vite configuration

Configure Vite to bundle @convex-dev/better-auth during server-side rendering, which avoids module resolution errors.

vite.config.ts
export default defineConfig({
  // ...other config
  ssr: {
    noExternal: ["@convex-dev/better-auth"],
  },
});

Update router config

Set expectAuth: true on the ConvexQueryClient in your router. Without it, authenticated data from server-side rendering is lost as soon as the page first renders.

Remove the unused Wrap provider if your router has one.

src/router.tsx
export function getRouter() {
  const convexUrl = (import.meta as any).env.VITE_CONVEX_URL!;
  if (!convexUrl) {
    throw new Error("VITE_CONVEX_URL is not set");
  }
  const convexQueryClient = new ConvexQueryClient(convexUrl, {
    expectAuth: true, 
  });

  const queryClient: QueryClient = new QueryClient({
    defaultOptions: {
      queries: {
        queryKeyHashFn: convexQueryClient.hashFn(),
        queryFn: convexQueryClient.queryFn(),
      },
    },
  });
  convexQueryClient.connect(queryClient);

  const router = createTanStackRouter({
    routeTree,
    defaultPreload: "intent",
    defaultErrorComponent: DefaultCatchBoundary,
    defaultNotFoundComponent: () => <NotFound />,
    Wrap: ({ children }) => (
      <ConvexProvider client={convexQueryClient.convexClient}>
        {children}
      </ConvexProvider>
    ),
    context: { queryClient, convexQueryClient },
    scrollRestoration: true,
  });
  setupRouterSsrQueryIntegration({
    router,
    queryClient,
  });

  return router;
}

Update root route

Change the root route to use the new getAuth() server function and the isAuthenticated context value.

src/routes/__root.tsx
import { createServerFn } from "@tanstack/react-start";
import {
  fetchSession,
  getCookieName,
} from "@convex-dev/better-auth/react-start";
import { getCookie, getRequest } from "@tanstack/react-start/server"; 
import { getToken } from "@/lib/auth-server"; 

const fetchAuth = createServerFn({ method: "GET" }).handler(async () => {
  const { createAuth } = await import("@convex/auth");
  const { session } = await fetchSession(getRequest());
  const sessionCookieName = getCookieName(createAuth);
  const token = getCookie(sessionCookieName);
  return {
    userId: session?.user.id,
    token,
  };
});

const getAuth = createServerFn({ method: "GET" }).handler(async () => {
  return await getToken();
});

export const Route = createRootRouteWithContext<{
  queryClient: QueryClient;
  convexQueryClient: ConvexQueryClient;
}>()({
  // ... other config
  beforeLoad: async (ctx) => {
    const token = await getAuth();

    // all queries, mutations and actions through TanStack Query will be
    // authenticated during SSR if we have a valid token
    if (token) {
      // During SSR only (the only time serverHttpClient exists),
      // set the auth token to make HTTP queries with.
      ctx.context.convexQueryClient.serverHttpClient?.setAuth(token);
    }

    return {
      isAuthenticated: !!token,
      token,
    };
  },
  component: RootComponent,
});

Reload on sign out

Update your sign-out functions to reload the page, so that expectAuth works correctly on the next sign-in. In apps with authenticated routes, the reload can usually replace a redirect.

src/lib/auth-client.ts
export const handleSignOut = async () => {
  const navigate = useNavigate(); 
  await authClient.signOut({
    fetchOptions: {
      onSuccess: () => {
        navigate({ to: "/" }); 
        location.reload(); 
      },
    },
  });
};

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.

Remove getStaticAuth

In convex/betterAuth/auth.ts, replace getStaticAuth(createAuth) with createAuth({} as any).

This file should contain only the auth export for schema generation. Importing it at runtime causes errors from missing environment variables.

convex/betterAuth/auth.ts
import { getStaticAuth } from "@convex-dev/better-auth"; 
import { v } from "convex/values";
import { createAuth } from "../auth";

// Export a static instance for Better Auth schema generation
export const auth = getStaticAuth(createAuth); 
export const auth = createAuth({} as any); 

Split out createAuthOptions function

Move your Better Auth options into a separate createAuthOptions function that returns them as a typed object, and pass its result to betterAuth(). With the options inside the betterAuth() call, the component had to run Better Auth to read them, which caused unnecessary logs and inaccurate error messages, and required workarounds such as optionsOnly.

convex/auth.ts
import {
  betterAuth,
  type BetterAuthOptions, 
} from "better-auth/minimal";

export const createAuthOptions = (ctx: GenericCtx<DataModel>) => {
  return {
    // ... auth config
  } satisfies BetterAuthOptions;
};

export const createAuth = (ctx: GenericCtx<DataModel>) => {
  return betterAuth({
    // ... auth config
  });
  return betterAuth(createAuthOptions(ctx)); 
};

Update adapter

In adapter.ts, pass createAuthOptions to createApi instead of createAuth, remove the migrationRemoveUserId export, which the component no longer provides, and export the consumeOne and incrementOne functions that Better Auth 1.7 adds.

convex/betterAuth/adapter.ts
import { createApi } from "@convex-dev/better-auth";
import {
  createAuth, 
  createAuthOptions, 
} from "../auth";
import schema from "./schema";

export const {
  create,
  findOne,
  findMany,
  updateOne,
  updateMany,
  deleteOne,
  deleteMany,
  migrationRemoveUserId, 
  consumeOne, 
  incrementOne, 
} = createApi(schema, createAuth); 
} = 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