clerk-migration-deep-dive

Migrate from other authentication providers to Clerk. Use when migrating from Auth0, Firebase, Supabase Auth, NextAuth, or custom authentication solutions. Trigger with phrases like "migrate to clerk", "clerk migration", "switch to clerk", "auth0 to clerk", "firebase auth to clerk".

1,868 stars

Best use case

clerk-migration-deep-dive is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Migrate from other authentication providers to Clerk. Use when migrating from Auth0, Firebase, Supabase Auth, NextAuth, or custom authentication solutions. Trigger with phrases like "migrate to clerk", "clerk migration", "switch to clerk", "auth0 to clerk", "firebase auth to clerk".

Teams using clerk-migration-deep-dive should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/clerk-migration-deep-dive/SKILL.md --create-dirs "https://raw.githubusercontent.com/jeremylongshore/claude-code-plugins-plus-skills/main/plugins/saas-packs/clerk-pack/skills/clerk-migration-deep-dive/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/clerk-migration-deep-dive/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How clerk-migration-deep-dive Compares

Feature / Agentclerk-migration-deep-diveStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Migrate from other authentication providers to Clerk. Use when migrating from Auth0, Firebase, Supabase Auth, NextAuth, or custom authentication solutions. Trigger with phrases like "migrate to clerk", "clerk migration", "switch to clerk", "auth0 to clerk", "firebase auth to clerk".

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Clerk Migration Deep Dive

## Current State
!`npm list @auth0/nextjs-auth0 next-auth @supabase/auth-helpers-nextjs firebase 2>/dev/null | grep -E "auth0|next-auth|supabase|firebase" || echo 'No auth providers detected'`

## Overview
Comprehensive guide to migrating from Auth0, Firebase Auth, Supabase Auth, or NextAuth to Clerk. Covers user data export, bulk import, parallel running, and phased migration.

## Prerequisites
- Current auth provider access with admin/export permissions
- Clerk account with API keys
- Git repository with clean working state
- Migration timeline planned (recommend 2-4 weeks)

## Instructions

### Step 1: Export Users from Current Provider

**Auth0 Export:**
```bash
# Export users via Auth0 Management API
curl -s -H "Authorization: Bearer $AUTH0_TOKEN" \
  "https://$AUTH0_DOMAIN/api/v2/users?per_page=100&page=0" \
  | jq '[.[] | {email: .email, name: .name, picture: .picture, created_at: .created_at}]' \
  > auth0-users.json
```

**NextAuth (Prisma) Export:**
```typescript
// scripts/export-nextauth-users.ts
const users = await prisma.user.findMany({
  include: { accounts: true },
})
const exported = users.map((u) => ({
  email: u.email,
  name: u.name,
  image: u.image,
  provider: u.accounts[0]?.provider,
  createdAt: u.createdAt,
}))
await fs.writeFile('nextauth-users.json', JSON.stringify(exported, null, 2))
```

### Step 2: Import Users to Clerk
```typescript
// scripts/import-to-clerk.ts
import { createClerkClient } from '@clerk/backend'
import users from './auth0-users.json'

const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })

interface MigrationResult {
  email: string
  status: 'created' | 'exists' | 'error'
  clerkId?: string
  error?: string
}

async function importUsers(): Promise<MigrationResult[]> {
  const results: MigrationResult[] = []

  for (const user of users) {
    try {
      const created = await clerk.users.createUser({
        emailAddress: [user.email],
        firstName: user.name?.split(' ')[0],
        lastName: user.name?.split(' ').slice(1).join(' '),
        skipPasswordRequirement: true, // User will set password on first sign-in
      })
      results.push({ email: user.email, status: 'created', clerkId: created.id })
      console.log(`Created: ${user.email} -> ${created.id}`)
    } catch (err: any) {
      if (err.status === 422) {
        results.push({ email: user.email, status: 'exists' })
      } else {
        results.push({ email: user.email, status: 'error', error: err.message })
      }
    }

    // Respect rate limits
    await new Promise((resolve) => setTimeout(resolve, 100))
  }

  return results
}

importUsers().then((results) => {
  const summary = {
    total: results.length,
    created: results.filter((r) => r.status === 'created').length,
    exists: results.filter((r) => r.status === 'exists').length,
    errors: results.filter((r) => r.status === 'error').length,
  }
  console.log('Migration summary:', summary)
  fs.writeFileSync('migration-results.json', JSON.stringify(results, null, 2))
})
```

### Step 3: Update Database References
```typescript
// scripts/update-db-references.ts
import { createClerkClient } from '@clerk/backend'

const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })

async function updateDatabaseReferences() {
  // Get all users from your database
  const dbUsers = await db.user.findMany()

  for (const dbUser of dbUsers) {
    // Find corresponding Clerk user by email
    const clerkUsers = await clerk.users.getUserList({
      emailAddress: [dbUser.email],
    })

    if (clerkUsers.totalCount > 0) {
      const clerkUser = clerkUsers.data[0]
      await db.user.update({
        where: { id: dbUser.id },
        data: {
          clerkId: clerkUser.id,
          // Keep old auth ID for rollback
          legacyAuthId: dbUser.authProviderId,
        },
      })
      console.log(`Mapped: ${dbUser.email} -> ${clerkUser.id}`)
    }
  }
}
```

### Step 4: Replace Auth Code (NextAuth to Clerk Example)
```typescript
// BEFORE: NextAuth
// import { getServerSession } from 'next-auth'
// import { authOptions } from '@/lib/auth'
// const session = await getServerSession(authOptions)
// const userId = session?.user?.id

// AFTER: Clerk
import { auth } from '@clerk/nextjs/server'
const { userId } = await auth()
```

```typescript
// BEFORE: NextAuth client hook
// import { useSession } from 'next-auth/react'
// const { data: session } = useSession()

// AFTER: Clerk client hook
import { useUser } from '@clerk/nextjs'
const { user, isLoaded } = useUser()
```

```typescript
// BEFORE: NextAuth middleware
// export { default } from 'next-auth/middleware'
// export const config = { matcher: ['/dashboard(.*)'] }

// AFTER: Clerk middleware
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
const isProtected = createRouteMatcher(['/dashboard(.*)'])
export default clerkMiddleware(async (auth, req) => {
  if (isProtected(req)) await auth.protect()
})
```

### Step 5: Parallel Running (Optional Safety Net)
```typescript
// lib/auth-bridge.ts — run both auth systems during transition
import { auth as clerkAuth } from '@clerk/nextjs/server'

export async function getAuthUser() {
  // Try Clerk first (new system)
  const { userId: clerkUserId } = await clerkAuth()
  if (clerkUserId) {
    return { provider: 'clerk', userId: clerkUserId }
  }

  // Fall back to legacy system during migration window
  // const legacySession = await getLegacySession()
  // if (legacySession) return { provider: 'legacy', userId: legacySession.userId }

  return null
}
```

### Step 6: Cleanup After Migration
```bash
# After migration is verified (2+ weeks in production):
npm uninstall next-auth @auth0/nextjs-auth0  # Remove old auth packages
# Delete old auth files: pages/api/auth/[...nextauth].ts, lib/auth.ts
# Remove legacy database columns after confirming all users migrated
```

## Output
- User export from current auth provider (Auth0, NextAuth, Firebase)
- Bulk import script with rate limiting and error handling
- Database reference mapping (old auth IDs to Clerk IDs)
- Code migration examples (NextAuth to Clerk)
- Parallel running bridge for safe transition
- Cleanup checklist for removing old auth code

## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| Duplicate email on import | User already exists in Clerk | Skip (status: 'exists') or merge |
| Invalid email format | Dirty data from export | Clean/validate before import |
| Rate limited during import | Too many API calls | Add 100ms delay between creates |
| Password can't be migrated | Passwords are hashed | Use `skipPasswordRequirement`, user sets new password |
| OAuth accounts | Social login tokens non-transferable | Users re-link OAuth accounts on first Clerk sign-in |

## Examples

### Migration Verification Script
```typescript
// scripts/verify-migration.ts
async function verifyMigration() {
  const dbUsers = await db.user.findMany({ where: { clerkId: { not: null } } })
  const unmapped = await db.user.findMany({ where: { clerkId: null } })

  console.log(`Mapped: ${dbUsers.length}, Unmapped: ${unmapped.length}`)

  if (unmapped.length > 0) {
    console.log('Unmapped users:', unmapped.map((u) => u.email))
  }
}
```

## Resources
- [Clerk Migration Overview](https://clerk.com/docs/deployments/migrate-overview)
- [Migrate from Auth0](https://clerk.com/docs/deployments/migrate-from-auth0)
- [Migrate from NextAuth](https://clerk.com/docs/deployments/migrate-from-nextauth)

## Next Steps
After migration, review `clerk-prod-checklist` for production readiness.

Related Skills

workhuman-upgrade-migration

1868
from jeremylongshore/claude-code-plugins-plus-skills

Workhuman upgrade migration for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman upgrade migration".

wispr-upgrade-migration

1868
from jeremylongshore/claude-code-plugins-plus-skills

Wispr Flow upgrade migration for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr upgrade migration".

windsurf-upgrade-migration

1868
from jeremylongshore/claude-code-plugins-plus-skills

Upgrade Windsurf IDE, migrate settings from VS Code or Cursor, and handle breaking changes. Use when upgrading Windsurf versions, migrating from another editor, or handling configuration changes after updates. Trigger with phrases like "upgrade windsurf", "windsurf update", "migrate to windsurf", "windsurf from cursor", "windsurf from vscode".

windsurf-migration-deep-dive

1868
from jeremylongshore/claude-code-plugins-plus-skills

Migrate to Windsurf from VS Code, Cursor, or other AI IDEs with full configuration transfer. Use when migrating a team to Windsurf, transferring Cursor rules, or evaluating Windsurf against other AI editors. Trigger with phrases like "migrate to windsurf", "switch to windsurf", "windsurf from cursor", "windsurf from copilot", "windsurf evaluation".

webflow-upgrade-migration

1868
from jeremylongshore/claude-code-plugins-plus-skills

Analyze, plan, and execute Webflow SDK upgrades (webflow-api v1 to v3) with breaking change detection, API v1-to-v2 migration, and deprecation handling. Trigger with phrases like "upgrade webflow", "webflow migration", "webflow breaking changes", "update webflow SDK", "webflow v1 to v2".

webflow-migration-deep-dive

1868
from jeremylongshore/claude-code-plugins-plus-skills

Execute major Webflow migrations — from other CMS platforms to Webflow CMS, between Webflow sites, or large-scale content re-architecture using the Data API v2 bulk endpoints, strangler fig pattern, and data validation. Trigger with phrases like "migrate to webflow", "webflow migration", "import into webflow", "webflow replatform", "move content to webflow", "webflow bulk import", "wordpress to webflow".

vercel-upgrade-migration

1868
from jeremylongshore/claude-code-plugins-plus-skills

Upgrade Vercel CLI, Node.js runtime, and Next.js framework versions with breaking change detection. Use when upgrading Vercel CLI versions, migrating Node.js runtimes, or updating Next.js between major versions on Vercel. Trigger with phrases like "upgrade vercel", "vercel migration", "vercel breaking changes", "update vercel CLI", "next.js upgrade on vercel".

vercel-migration-deep-dive

1868
from jeremylongshore/claude-code-plugins-plus-skills

Migrate to Vercel from other platforms or re-architecture existing Vercel deployments. Use when migrating from Netlify, AWS, or Cloudflare to Vercel, or when re-platforming an existing Vercel application. Trigger with phrases like "migrate to vercel", "vercel migration", "switch to vercel", "netlify to vercel", "aws to vercel", "vercel replatform".

veeva-upgrade-migration

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault upgrade migration for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva upgrade migration".

veeva-migration-deep-dive

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault migration deep dive for enterprise operations. Use when implementing advanced Veeva Vault patterns. Trigger: "veeva migration deep dive".

vastai-upgrade-migration

1868
from jeremylongshore/claude-code-plugins-plus-skills

Upgrade Vast.ai CLI, migrate API versions, and handle breaking changes. Use when upgrading vastai CLI, detecting deprecations, or migrating between API versions. Trigger with phrases like "upgrade vastai", "vastai migration", "vastai breaking changes", "update vastai CLI".

vastai-migration-deep-dive

1868
from jeremylongshore/claude-code-plugins-plus-skills

Migrate GPU workloads to or from Vast.ai, or between GPU providers. Use when switching from AWS/GCP/Azure GPU instances to Vast.ai, migrating between GPU types, or re-platforming ML infrastructure. Trigger with phrases like "migrate to vastai", "vastai migration", "switch to vastai", "vastai from aws", "vastai from lambda".