Skip to content

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.

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 accountId unchanged for every provider except credential, 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, team and invitation. Each column that stores a user id needs a rewrite; the last script step handles any table and column you name.
Terminal window
npx convex export --path pre-migration.zip

Unzip it. The component’s tables are under _components/betterAuth/<table>/documents.jsonl. This file is also your way back: convex import restores it.

Follow Add VexCMS to an existing Next.js app, with these differences:

  • Remove the component. Delete app.use(betterAuth) from convex/convex.config.ts, and your createClient(components.betterAuth) auth file. VexCMS’s convex/auth/ replaces it, and its convex/http.ts routes replace authComponent.registerRoutes.
  • Keep the same secret and site URL. Leave BETTER_AUTH_SECRET and SITE_URL on the deployment as they are. Better Auth encrypts each TOTP secret with BETTER_AUTH_SECRET, so a different secret makes every two-factor check fail with invalid tag.
  • Keep the same cookie prefix. Set AUTH_COOKIE_PREFIX in src/db/constants/auth.ts to the prefix your app already uses: "better-auth" unless you set advanced.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(), to convex/auth/plugins/index.ts, and list it under plugins in convex/auth/schema.ts, so vex dev generates 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:

convex/schema.ts
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.

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):

Terminal window
mkdir -p staging
for 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"
done

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.

convex/migrateBetterAuth.ts
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.

In this order, with your own email for promoteEmail so you can open /admin afterwards. Add --prod to each command when you migrate production.

Terminal window
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:

Terminal window
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.

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.

Run clearStaging for each staging table until it returns {"isDone": true}:

Terminal window
npx convex run migrateBetterAuth:clearStaging '{"table":"user"}'

Then delete the migration_betterAuth_* tables from convex/schema.ts, delete convex/migrateBetterAuth.ts, and push again.