Skip to content

Better Auth - Backfill scripts - #4285

Open
devkiran wants to merge 10 commits into
better-auth-1from
better-auth-2
Open

Better Auth - Backfill scripts #4285
devkiran wants to merge 10 commits into
better-auth-1from
better-auth-2

Conversation

@devkiran

@devkiran devkiran commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Added automated migration workflows for users, accounts, and credentials.
    • Migrations process records in manageable batches and continue automatically until complete.
    • Added migration verification to confirm that all eligible records were processed.
    • Migration progress and completion status are reported during execution.

@vercel

vercel Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
dub Ready Ready Preview Aug 7, 2026 11:43am

Request Review

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: cc84c745-9929-457e-babb-bc1232905865

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This change adds three Better Auth migration cron routes and a script that triggers them through QStash. Each route processes records in batches, schedules follow-up work, and supports completion verification through Prisma counts.

Changes

Better Auth migration

Layer / File(s) Summary
Migration triggers and scheduling
apps/web/scripts/better-auth/migrate.ts
The script publishes user, account, and credential migration messages through QStash with sequential execution settings.
Batched migration routes
apps/web/app/(ee)/api/cron/better-auth/migrate-users/route.ts, apps/web/app/(ee)/api/cron/better-auth/migrate-accounts/route.ts, apps/web/app/(ee)/api/cron/better-auth/migrate-credentials/route.ts
The routes process up to 1,000 records per batch, run for up to 10 iterations, log progress, and schedule delayed follow-up requests when records remain.
Migration verification
apps/web/scripts/better-auth/migrate.ts
The script checks remaining user, account, and credential records and exits with status 1 when migration is incomplete.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Script as migrate.ts
  participant QStash
  participant Route as Better Auth cron route
  participant Prisma
  Script->>QStash: Publish migration request
  QStash->>Route: Invoke POST endpoint
  Route->>Prisma: Process one migration batch
  Prisma-->>Route: Return batch result
  Route->>QStash: Schedule next batch if needed
  Script->>Prisma: Verify remaining records
  Prisma-->>Script: Return migration counts
Loading

Possibly related PRs

  • dubinc/dub#4284: Introduces the Better Auth schema fields used by these migration routes.

Suggested reviewers: steven-tey

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the added Better Auth backfill migration scripts and cron endpoints.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch better-auth-2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@devkiran
devkiran requested a review from steven-tey August 7, 2026 10:38
@devkiran devkiran changed the title Better Auth - Migration scripts Better Auth - Backfill scripts Aug 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/web/scripts/better-auth/migrate.ts (1)

8-55: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a CLI argument instead of commented-out calls.

Lines 9-11 comment out the three migration triggers. In the committed state, migrateUsers, migrateAccounts, and migrateCredentials are unreachable. The three functions also differ only by route path and flow control key. A single helper plus an argument switch removes both problems.

♻️ Proposed refactor
-async function main() {
-  // await migrateUsers();
-  // await migrateAccounts();
-  // await migrateCredentials();
-  await verifyMigration();
-}
-
-async function migrateUsers() {
-  const qstashResponse = await qstash.publishJSON({
-    method: "POST",
-    url: `${APP_DOMAIN_WITH_NGROK}/api/cron/better-auth/migrate-users`,
-    retries: 0,
-    flowControl: {
-      key: "better-auth-migrate-users",
-      parallelism: 1,
-    },
-  });
-
-  console.log(`migrateUsers executed: ${qstashResponse.messageId}`);
-}
-
-async function migrateAccounts() {
-  const qstashResponse = await qstash.publishJSON({
-    method: "POST",
-    url: `${APP_DOMAIN_WITH_NGROK}/api/cron/better-auth/migrate-accounts`,
-    retries: 0,
-    flowControl: {
-      key: "better-auth-migrate-accounts",
-      parallelism: 1,
-    },
-  });
-
-  console.log(`migrateAccounts executed: ${qstashResponse.messageId}`);
-}
-
-async function migrateCredentials() {
-  const qstashResponse = await qstash.publishJSON({
-    method: "POST",
-    url: `${APP_DOMAIN_WITH_NGROK}/api/cron/better-auth/migrate-credentials`,
-    retries: 0,
-    flowControl: {
-      key: "better-auth-migrate-credentials",
-      parallelism: 1,
-    },
-  });
-
-  console.log(`migrateCredentials executed: ${qstashResponse.messageId}`);
-}
+const STEPS = ["users", "accounts", "credentials"] as const;
+type Step = (typeof STEPS)[number];
+
+async function main() {
+  const step = process.argv[2];
+
+  if (STEPS.includes(step as Step)) {
+    await trigger(step as Step);
+    return;
+  }
+
+  await verifyMigration();
+}
+
+async function trigger(step: Step) {
+  const { messageId } = await qstash.publishJSON({
+    method: "POST",
+    url: `${APP_DOMAIN_WITH_NGROK}/api/cron/better-auth/migrate-${step}`,
+    retries: 0,
+    flowControl: {
+      key: `better-auth-migrate-${step}`,
+      parallelism: 1,
+    },
+  });
+
+  console.log(`migrate-${step} triggered: ${messageId}`);
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/scripts/better-auth/migrate.ts` around lines 8 - 55, Replace the
commented-out calls in main with a CLI argument switch that selects users,
accounts, or credentials migration, while preserving verifyMigration as the
default or explicit option as appropriate. Consolidate migrateUsers,
migrateAccounts, and migrateCredentials into one parameterized migration helper
that derives the endpoint route and flow-control key from the selected migration
type, and invoke it from main.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/app/`(ee)/api/cron/better-auth/migrate-credentials/route.ts:
- Around line 33-48: In the migration loop after prisma.account.createMany, add
the same count === 0 progress guard used by migrate-users and migrate-accounts:
call logAndRespond with an error response before continuing or scheduling
another batch. Confirm and use the existing second-argument convention for
marking errors, while preserving normal logging and completion behavior when
count is positive.

In `@apps/web/app/`(ee)/api/cron/better-auth/migrate-users/route.ts:
- Around line 7-13: Add the deployment plan's 300-second maxDuration export
beside the existing dynamic export in
apps/web/app/(ee)/api/cron/better-auth/migrate-users/route.ts (lines 7-13),
migrate-accounts/route.ts (lines 7-13), and migrate-credentials/route.ts (lines
7-13); no other changes are required.

---

Nitpick comments:
In `@apps/web/scripts/better-auth/migrate.ts`:
- Around line 8-55: Replace the commented-out calls in main with a CLI argument
switch that selects users, accounts, or credentials migration, while preserving
verifyMigration as the default or explicit option as appropriate. Consolidate
migrateUsers, migrateAccounts, and migrateCredentials into one parameterized
migration helper that derives the endpoint route and flow-control key from the
selected migration type, and invoke it from main.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3c7e6b39-bd29-438c-80a1-f37f7501800f

📥 Commits

Reviewing files that changed from the base of the PR and between 2bb37b3 and ca7fd6a.

📒 Files selected for processing (4)
  • apps/web/app/(ee)/api/cron/better-auth/migrate-accounts/route.ts
  • apps/web/app/(ee)/api/cron/better-auth/migrate-credentials/route.ts
  • apps/web/app/(ee)/api/cron/better-auth/migrate-users/route.ts
  • apps/web/scripts/better-auth/migrate.ts

Comment on lines +33 to +48
if (users.length === 0) {
return logAndRespond("Finished migrating credentials.");
}

const { count } = await prisma.account.createMany({
skipDuplicates: true,
data: users.map((user) => ({
userId: user.id,
accountId: user.id,
providerId: "credential",
password: user.passwordHash,
})),
});

console.log(`Migrated ${count} credentials.`);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Add a progress guard. The batch can repeat forever.

createMany uses skipDuplicates: true. The returned count is logged but never checked. If count is 0 while users.length is greater than 0, the findMany filter still matches the same users on the next iteration. The loop then processes the same 1000 rows 10 times and schedules another QStash message. retries: 0 does not stop this, because each run publishes a new message. The chain repeats every 10 seconds without end.

migrate-users and migrate-accounts both exit on count === 0. This route needs the same guard.

🐛 Proposed fix
     const { count } = await prisma.account.createMany({
       skipDuplicates: true,
       data: users.map((user) => ({
         userId: user.id,
         accountId: user.id,
         providerId: "credential",
         password: user.passwordHash,
       })),
     });
 
     console.log(`Migrated ${count} credentials.`);
+
+    // No rows inserted while candidates remain means the batch cannot progress.
+    if (count === 0) {
+      return logAndRespond(
+        `Stopped migrating credentials: ${users.length} users matched but no accounts were created.`,
+        true,
+      );
+    }
   }

Confirm the second argument of logAndRespond marks an error response before you apply it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/app/`(ee)/api/cron/better-auth/migrate-credentials/route.ts around
lines 33 - 48, In the migration loop after prisma.account.createMany, add the
same count === 0 progress guard used by migrate-users and migrate-accounts: call
logAndRespond with an error response before continuing or scheduling another
batch. Confirm and use the existing second-argument convention for marking
errors, while preserving normal logging and completion behavior when count is
positive.

Comment on lines +7 to +13
export const dynamic = "force-dynamic";

const BATCH_SIZE = 1000;
const ITERATIONS = 10;

// POST /api/cron/better-auth/migrate-users
export const POST = withCron(async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

No migration route declares maxDuration. All three routes run up to 10 sequential batches of 1000 records in a single request but export only dynamic = "force-dynamic". If the platform default timeout ends a request, retries: 0 prevents a QStash retry, and the migration chain stops without publishing the follow-up message.

  • apps/web/app/(ee)/api/cron/better-auth/migrate-users/route.ts#L7-L13: add export const maxDuration = 300; next to the dynamic export.
  • apps/web/app/(ee)/api/cron/better-auth/migrate-accounts/route.ts#L7-L13: add the same maxDuration export; the raw UPDATE ... LIMIT 1000 loop carries the same timeout risk.
  • apps/web/app/(ee)/api/cron/better-auth/migrate-credentials/route.ts#L7-L13: add the same maxDuration export; this route runs two queries per iteration, so it is the slowest of the three.

Match the value to the plan limit for this deployment.

📍 Affects 3 files
  • apps/web/app/(ee)/api/cron/better-auth/migrate-users/route.ts#L7-L13 (this comment)
  • apps/web/app/(ee)/api/cron/better-auth/migrate-accounts/route.ts#L7-L13
  • apps/web/app/(ee)/api/cron/better-auth/migrate-credentials/route.ts#L7-L13
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/app/`(ee)/api/cron/better-auth/migrate-users/route.ts around lines 7
- 13, Add the deployment plan's 300-second maxDuration export beside the
existing dynamic export in
apps/web/app/(ee)/api/cron/better-auth/migrate-users/route.ts (lines 7-13),
migrate-accounts/route.ts (lines 7-13), and migrate-credentials/route.ts (lines
7-13); no other changes are required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant