Migrate from another platform
A source maps one platform's export onto Clerk's import schema, and says what it brings across. The Clerk CLI ships seven: clerk, auth0, authjs, betterauth, firebase, supabase, and workos. For anything else, write your own and pass it with --source ./my-platform.ts. The CLI loads your source file at runtime, without a rebuild.
Write a source with an AI agent
Clerk's clerk-migrate skill can write the source for you. Install Clerk's skills:
npx skills add clerk/skillsThen give your agent the export file and ask it to write a Clerk migration source for it. The skill asks about the details below, writes the file, and loads it with clerk migrate sources ./my-platform.ts to check it.
Before you write a source
- How the platform records verification: A boolean (
email_verified: true), a nullable timestamp (confirmed_at: "2024-06-29T…"), or not at all. Clerk creates primary identifiers as verified, so route any address the platform never confirmed tounverifiedEmailAddressesinstead ofemail. See unverified emails and phones for how the import creates them. - The password hash algorithm: Clerk verifies each hash as-is, so
passwordHashermust match that algorithm. Get the accepted values frompassword_hasherin theCreateUserBackend API reference. The CLI rejects unsupportedpasswordHashervalues before importing users and lists the accepted values in the error. It also rejects a password whose shape doesn't match its hasher, such as a bcrypt digest with a cost above 15. - The export's shape: If the export nests the user array or omits CSV headers, use
preTransformto extract arrays such as{ "records": [...] }or supply the headers.
Write the file
Create the source file in your project and export a source definition. It can import your project's files, but it can't import from the CLI.
The CLI reads --source as a path when it starts with ./, ../, or /, or ends in .ts, .js, or .mjs, and resolves it from the current directory.
export default {
key: 'myplatform',
label: 'My Platform',
description: "Exports from My Platform's admin console.",
transformer: {
account_ref: 'userId',
contact_email: 'email',
email_ok: 'emailVerified',
given: 'firstName',
family: 'lastName',
pw_bcrypt: 'password',
},
carries: {
passwords: { level: 'yes', note: 'bcrypt hashes from the pw_bcrypt column.' },
mfa: { level: 'no', note: 'Not exported.' },
metadata: { level: 'no', note: 'Not exported.' },
},
defaults: { passwordHasher: 'bcrypt' },
postTransform: (user) => {
// This platform records verification as a boolean. An address it never
// confirmed must not become a verified primary identifier. A CSV writes
// it as a string, such as 'TRUE' or '1'.
const verified = ['true', '1', 'yes', 'y', 't'].includes(
String(user.emailVerified).trim().toLowerCase(),
)
if (!verified) {
user.unverifiedEmailAddresses = user.email
delete user.email
}
delete user.emailVerified
},
}TypeScript works, including interface, satisfies, and as const. Plain .js works too.
Map a field to userId
A source field must map to userId. It becomes the Clerk user's external_id, which is how a re-run of the import recognizes users it already created. Without it the import would create every user with no external_id, so the CLI refuses to load a source that doesn't map one.
Unwrap a nested export
preTransform runs before field mapping and can hand back the users it found:
export default {
// …key, label and field map as above…
preTransform: (filePath, fileType) => {
if (fileType === 'application/json') {
const parsed = JSON.parse(require('node:fs').readFileSync(filePath, 'utf-8'))
return { filePath, data: Array.isArray(parsed) ? parsed : parsed.records }
}
return { filePath }
},
}For a CSV with no header row, return the column names as csvHeaders, for example { filePath, csvHeaders: ['id', 'email', 'name'] }. Otherwise the parser reads your first user as the column names.
preTransform doesn't run on a file written by clerk migrate export.
Schema fields
The CLI validates each user against this schema before it sends any requests. It drops fields outside the schema and lists them under Clerk won't store. Use the field names below. Every user needs userId (string).
Identifiers
At least one must be present, or the import's checks reject the user. Each email and phone field accepts a single value or an array.
Profile, password, and two-factor authentication (2FA)
Metadata
unsafeMetadata is readable and writable by the client, so never put anything you trust there. publicMetadata is client-readable and server-writable. privateMetadata is server-side only.
Account state
The account state fields are createdAt, legalAcceptedAt, banned, bypassClientTrust, createOrganizationEnabled, createOrganizationsLimit, deleteSelfEnabled, skipLegalChecks, skipPasswordChecks. Map createdAt if the source has an original signup date. Without it, a migrated user's creation date is the day of the import. If a ban has an end date, also set banEndsAt so the checks warn you that the ban won't expire in Clerk.
Leave a user out
Set skipReason to a string in postTransform. The import records that user as skipped with your reason and continues without requiring --allow-partial. Built-in sources use it for soft-deleted users, anonymous users, and users with no email or phone.
Drop a password
If your source drops a hash it can't use, set passwordDropped: true on that user, and the checks count it in their warning about passwords Clerk can't verify.
Check your source
clerk migrate sources loads and validates your file without touching any data, and shows where each field lands:
clerk migrate sources ./my-platform.tsmyplatform My Platform (custom — ./my-platform.ts)
Exports from My Platform's admin console.
What comes across
Passwords yes
bcrypt hashes from the pw_bcrypt column.
MFA no
Not exported.
Metadata no
Not exported.
Where each field lands
account_ref → userId
contact_email → email
email_ok → emailVerified not a Clerk field: Clerk won't store it unless postTransform moves it
given → firstName
family → lastName
pw_bcrypt → password
passwordHasher is always "bcrypt"
Social sign-ins are not copied. Enable the same providers in Clerk, and a user
who signs in with one is linked to their imported account by verified email. See
https://clerk.com/docs/guides/configure/auth-strategies/social-connections/account-linkingThe example uses emailVerified as an intermediate value and removes it in postTransform.
The CLI checks your file's shape before using it, and names the specific problem. The last four messages start with <path> is not a valid source:.
Run the migration
Install the Clerk CLI, sign in, and link the project directory you'll run the migration from to the Clerk application you're importing into:
npm install -g clerk
clerk auth login
clerk linkTo skip clerk auth login and clerk link, set CLERK_SECRET_KEY to the of the instance you're importing into, or pass it with --secret-key.
To skip the global install, replace clerk with npx clerk@latest in each command. To update an existing install, run clerk update.
import and undo target the linked application's development instance by default. Pass --instance prod or a full instance ID to choose another. With a Secret Key, the key picks the instance, so pass the production instance's key to import into production. For other ways to pick the instance and Secret Key, see choose the destination instance.
The CLI stores each run in .clerk/migrate/<run_id>/ and adds .clerk/ to .gitignore. To store runs elsewhere, see command behavior.
Check the file against your Clerk instance first. --dry-run runs every check and writes nothing:
clerk migrate import users.json --source ./my-platform.ts --dry-runReview the Clerk won't store warning for fields your mapping produces outside the import schema.
Read the checks closely on a first custom migration. See check before you import for the full list.
When the checks pass, rerun your dry-run command with --yes instead of --dry-run, keeping the input and all other flags.
The run records your source's key and a hash of the source file. After you edit the source, the CLI refuses to continue the earlier run and identifies it. To reimport the whole export with the edited source, undo the earlier run first. --new-run starts a new run without undoing, but the checks reject every user the earlier run created as already in the instance, so the import stops unless you pass --allow-partial. The hash covers only the source file, so after you edit a helper file it imports, undo the earlier run the same way.
Use the import run's ID to check its results or undo it.
Verify the migration
-
Read what the run did. It lists the users that failed or were skipped, and why:
terminal clerk migrate runs <import_run_id> -
Confirm the users exist, and that
external_idis populated. The table view doesn't showexternal_id, so ask for JSON:terminal clerk users list --json -
Sign in as a migrated user. If you mapped a password, only a sign-in confirms you named the right hasher.
Undo the migration
Preview the users the import created, using the import run's ID:
clerk migrate undo <import_run_id> --dry-runThen delete them:
clerk migrate undo <import_run_id> --yes--yes doesn't delete users who have signed in since the import. Add --include-signed-in to authorize those deletions too. Confirming at the interactive prompt also authorizes them.
Pass the same --instance, --app, or --secret-key you gave the import. See undo an import for confirmation rules, refusal conditions, and retries.
Next steps
Foreign keys
Keep referencing your users by the IDs they had before the migration.
How the CLI migrates users
Learn how the CLI checks users, continues an interrupted import, and undoes one.
Account linking
Learn how Clerk links a social sign-in to an imported user.
Feedback
Last updated on