Migrate from the Better Auth component
An app set up with the @convex-dev/better-auth Convex component keeps Better Auth’s tables
inside the component. VexCMS keeps them in your app’s own schema, so the admin can list users and
check their roles. This guide moves the data across on the same deployment. Users keep their
passwords, their TOTP two-factor secrets, and their signed-in sessions.
Every user gets a new id. Convex numbers each table, and the component’s table numbers
overlap your app’s own, so importing rows with their old _ids fails, almost always on user.
Instead, you import every row without its _id and rewrite each column that held the old user
id: Better Auth’s own userId columns and any column of yours that stores it.
What this covers
Section titled “What this covers”Tested with email and password sign-in, TOTP two-factor, and two app tables storing the user id as
a string (on convex@1.49.0, better-auth@1.7.18, @convex-dev/better-auth@0.13.0). Not tested:
- OAuth accounts. The script leaves
accountIdunchanged for every provider exceptcredential, because for OAuth providers it holds the provider’s own user id. Sign in once with each provider you use to confirm it still finds the account. - Other plugin tables, such as
apikey,organization,member,teamandinvitation. Each column that stores a user id needs a rewrite; the last script step handles any table and column you name.
1. Back up
Section titled “1. Back up”npx convex export --path pre-migration.zippnpm convex export --path pre-migration.zipyarn convex export --path pre-migration.zipbunx convex export --path pre-migration.zipdeno x convex export --path pre-migration.zipUnzip it. The component’s tables are under _components/betterAuth/<table>/documents.jsonl. This
file is also your way back: convex import restores it.
2. Switch to the VexCMS auth wiring
Section titled “2. Switch to the VexCMS auth wiring”Follow Add VexCMS to an existing Next.js app, with these differences:
- Remove the component. Delete
app.use(betterAuth)fromconvex/convex.config.ts, and yourcreateClient(components.betterAuth)auth file. VexCMS’sconvex/auth/replaces it, and itsconvex/http.tsroutes replaceauthComponent.registerRoutes. - Keep the same secret and site URL. Leave
BETTER_AUTH_SECRETandSITE_URLon the deployment as they are. Better Auth encrypts each TOTP secret withBETTER_AUTH_SECRET, so a different secret makes every two-factor check fail withinvalid tag. - Keep the same cookie prefix. Set
AUTH_COOKIE_PREFIXinsrc/db/constants/auth.tsto the prefix your app already uses:"better-auth"unless you setadvanced.cookiePrefix. With a different prefix, the browser’s session cookie no longer matches, and everyone is signed out even though their sessions migrated. - Enable the same Better Auth plugins. Add every plugin you use, such as
twoFactor(), toconvex/auth/plugins/index.ts, and list it underpluginsinconvex/auth/schema.ts, sovex devgenerates its tables and fields.
Then add one staging table per Better Auth table to convex/schema.ts. They hold the imported
rows until the script copies them:
import { v } from "convex/values"
export default defineSchema({ // ...your tables and the VexCMS tables
migration_betterAuth_user: defineTable(v.any()).index("by_legacyId", ["legacyId"]), migration_betterAuth_session: defineTable(v.any()), migration_betterAuth_account: defineTable(v.any()), migration_betterAuth_verification: defineTable(v.any()), migration_betterAuth_twoFactor: defineTable(v.any()), migration_betterAuth_jwks: defineTable(v.any()),})Drop twoFactor here and in the steps below if you don’t use it. Push with vex dev (or
vex dev --once). Convex unmounts the component; your backup still holds its data.
3. Import into the staging tables
Section titled “3. Import into the staging tables”Each row goes in without its _id and _creationTime, keeping the old id as legacyId. Staging
tables are new, so nothing can collide. Run from the folder you unzipped the backup into (needs
jq):
mkdir -p stagingfor t in user session account verification twoFactor jwks; do jq -c '. + {legacyId: ._id} | del(._id, ._creationTime)' \ "_components/betterAuth/$t/documents.jsonl" > "staging/$t.jsonl" npx convex import --table "migration_betterAuth_$t" --replace -y "staging/$t.jsonl"done4. Add the migration script
Section titled “4. Add the migration script”Every function processes one page and returns isDone and a cursor. Run it again, passing the
cursor back, until isDone is true. Re-running is safe: copied rows are marked and skipped.
import { v } from "convex/values"
import type { WithoutSystemFields } from "convex/server"
import type { Doc, Id, TableNames } from "./_generated/dataModel"import { internalMutation } from "./_generated/server"
const BATCH_SIZE = 200
/** Convex exports an unset optional field as `null`, which `v.optional` rejects. */function dropNullValues(doc: Record<string, unknown>) { return Object.fromEntries(Object.entries(doc).filter(([, value]) => value !== null))}
/** Copies users. `promoteEmail` gets the `admin` role; everyone else gets `user`. */export const migrateUsers = internalMutation({ args: { cursor: v.optional(v.string()), promoteEmail: v.optional(v.string()) }, handler: async (ctx, { cursor, promoteEmail }) => { const page = await ctx.db .query("migration_betterAuth_user") .paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE }) for (const row of page.page) { if (row.migrated) continue const { _id, _creationTime, legacyId, migrated, newId: _newId, ...doc } = row const roles = doc.email === promoteEmail ? ["user", "admin"] : ["user"] const newId = await ctx.db.insert("user", { ...dropNullValues(doc), roles, } as WithoutSystemFields<Doc<"user">>) await ctx.db.patch(_id, { migrated: true, newId }) } return { cursor: page.continueCursor, isDone: page.isDone } },})
/** Copies a table whose rows point at a user, rewriting `userId` (and the credential `accountId`). */export const migrateUserRows = internalMutation({ args: { table: v.union(v.literal("session"), v.literal("account"), v.literal("twoFactor")), cursor: v.optional(v.string()), }, handler: async (ctx, { table, cursor }) => { const page = await ctx.db .query(`migration_betterAuth_${table}`) .paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE }) for (const row of page.page) { if (row.migrated) continue const { _id, _creationTime, legacyId, migrated, newId: _newId, userId, ...doc } = row const user = await ctx.db .query("migration_betterAuth_user") .withIndex("by_legacyId", (q) => q.eq("legacyId", userId)) .unique() if (!user?.newId) throw new Error(`No migrated user for ${table} row ${legacyId}. Run migrateUsers first.`) const fields = dropNullValues(doc) if (table === "account" && fields.providerId === "credential") fields.accountId = user.newId const newId = await ctx.db.insert(table, { ...fields, userId: user.newId, } as WithoutSystemFields<Doc<"session" | "account" | "twoFactor">>) await ctx.db.patch(_id, { migrated: true, newId }) } return { cursor: page.continueCursor, isDone: page.isDone } },})
/** Copies a table with no user column as it is. */export const migratePlainRows = internalMutation({ args: { table: v.union(v.literal("verification"), v.literal("jwks")), cursor: v.optional(v.string()) }, handler: async (ctx, { table, cursor }) => { const page = await ctx.db .query(`migration_betterAuth_${table}`) .paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE }) for (const row of page.page) { if (row.migrated) continue const { _id, _creationTime, legacyId, migrated, newId: _newId, ...doc } = row const newId = await ctx.db.insert(table, dropNullValues(doc) as WithoutSystemFields<Doc<"verification" | "jwks">>) await ctx.db.patch(_id, { migrated: true, newId }) } return { cursor: page.continueCursor, isDone: page.isDone } },})
/** Rewrites one of your own columns that stores a user id, e.g. `posts.authorId`. */export const remapUserIdColumn = internalMutation({ args: { table: v.string(), column: v.string(), cursor: v.optional(v.string()) }, handler: async (ctx, { table, column, cursor }) => { const page = await ctx.db .query(table as TableNames) .paginate({ cursor: cursor ?? null, numItems: BATCH_SIZE }) for (const row of page.page as Array<Record<string, unknown>>) { const oldId = row[column] if (typeof oldId !== "string") continue const user = await ctx.db .query("migration_betterAuth_user") .withIndex("by_legacyId", (q) => q.eq("legacyId", oldId)) .unique() if (user?.newId) await ctx.db.patch(row._id as Id<TableNames>, { [column]: user.newId }) } return { cursor: page.continueCursor, isDone: page.isDone } },})
/** Empties a staging table, one page per call. */export const clearStaging = internalMutation({ args: { table: v.string() }, handler: async (ctx, { table }) => { const rows = await ctx.db.query(`migration_betterAuth_${table}` as TableNames).take(BATCH_SIZE) for (const row of rows) await ctx.db.delete(row._id) return { isDone: rows.length === 0 } },})remapUserIdColumn skips values that aren’t an old user id, so running it twice on the same
column does nothing the second time.
5. Run it
Section titled “5. Run it”In this order, with your own email for promoteEmail so you can open /admin afterwards. Add
--prod to each command when you migrate production.
npx convex run migrateBetterAuth:migrateUsers '{"promoteEmail":"you@example.com"}'npx convex run migrateBetterAuth:migrateUserRows '{"table":"session"}'npx convex run migrateBetterAuth:migrateUserRows '{"table":"account"}'npx convex run migrateBetterAuth:migrateUserRows '{"table":"twoFactor"}'npx convex run migrateBetterAuth:migratePlainRows '{"table":"verification"}'npx convex run migrateBetterAuth:migratePlainRows '{"table":"jwks"}'Then once for every column of yours that stores a Better Auth user id:
npx convex run migrateBetterAuth:remapUserIdColumn '{"table":"posts","column":"authorId"}'A result of {"isDone": false, "cursor": "..."} means there’s another page: run the same command
again with "cursor" added to its arguments.
6. Check it
Section titled “6. Check it”Checking that the rows exist isn’t enough. In testing, password sign-in failed while every row
looked correct, until the credential account’s accountId was rewritten too. So, as a real user:
- Reload a page where you were signed in before the migration. You should still be signed in.
- Sign out, then sign in with your password.
- Open
/admin. - Load a page of your own that reads one of the rewritten columns.
7. Clean up
Section titled “7. Clean up”Run clearStaging for each staging table until it returns {"isDone": true}:
npx convex run migrateBetterAuth:clearStaging '{"table":"user"}'Then delete the migration_betterAuth_* tables from convex/schema.ts, delete
convex/migrateBetterAuth.ts, and push again.