On this page

Guides

Migrating from Clerk to Entro Auth

A step-by-step guide to transitioning from Clerk to Entro Auth.

In this guide, we'll walk through the steps to migrate a project from Clerk to Entro Auth — including email/password with proper hashing, social/external accounts, phone number, two-factor data, and more.

Warning

This migration will invalidate all active sessions. This guide doesn't currently show you how to migrate Organization but it should be possible with additional steps and the Organization Plugin.

There are two ways to bring users over:

Both paths share the same rules about IDs and emails, and the same cutover.

Keep the Clerk user ID

The new user.id must be the Clerk user ID. Your app's own data is keyed on it: profile rows, billing customers whose external or reference ID is the Clerk ID, and foreign keys to either. If Entro Auth generates a new ID instead, a returning user who signs in with an emailed code lands in a new, empty account, or the insert fails on their email.

  • Insert with forceAllowId: true. Without it the adapter ignores the id you pass, logs a warning, and generates its own.
  • Keep the default string IDs. Don't set advanced.database.generateId to "uuid" or "serial" for a Clerk migration. With "uuid", a forced ID that is not a UUID is discarded with a logged warning and a new UUID is used. With "serial", the id column is numeric, and a forced ID that is not a number is dropped without a warning so the database assigns one. A Clerk ID is neither.
  • Store emails lowercase. Entro Auth lowercases the address it looks up and compares it with the stored value using the database's own equality. On a case-sensitive comparison (the Postgres default), a row stored as Person@Example.com is not found, and that user is treated as new.

Assess your app

Before changing anything, list every place that holds the Clerk user ID or depends on a Clerk session. Search for @clerk/ imports, clerk, userId, and stored IDs with Clerk's user_ prefix (the prefix and Clerk's helper names are Clerk's conventions, not confirmed here; check them against your Clerk SDK). Check:

  1. Profile and settings tables (for example a clerk_user_id column), and every foreign key to them.
  2. Billing customers whose external or reference ID is the Clerk ID.
  3. Clerk webhooks that create or update rows. Replace them with database hooks, and disable the endpoint in Clerk at cutover.
  4. Released native or desktop builds that send Clerk tokens to your API.
  5. OAuth or MCP clients (for example AI assistant connectors) that users authorized through Clerk.
  6. Organizations. This guide does not migrate them.
  7. The sign-in methods your users have today: password, providers, emailed codes, TOTP, phone.
  8. Who may sign up today. A Clerk instance can leave sign-up open, restrict it, or put it behind a waitlist or an allowlist (Clerk's names; read the setting in your Clerk dashboard). If it is anything but open, turn sign-up off on every method you enable here (disableSignUp) and add people another way. Otherwise the first emailed code to a new address makes an account your app never used to hand out.
  9. Every call to Clerk's auth.protect(). It guards two kinds of caller, and they need different answers: a page sends a signed-out visitor to sign in, a route handler answers 401. See What breaks at cutover.
  10. Users with more than one verified email address. An account here has one address, and a second one does not carry over. If your app decides anything by a verified address (a domain match, an invitation, a claim), settle which address the account keeps and tell the people affected.
  11. Where profile images come from. An image set in Clerk's profile, or copied from a provider, is served from Clerk's hosts and stops loading once the Clerk application is deleted. Without a provider, nothing sets image here unless your app does.
  12. Where a person lands after signing in and after signing up. Clerk's fallback redirect settings can live in environment variables rather than in code; Clerk.buildAfterSignInUrl() in the live site's console gives the value in effect.
  13. What you keep in Clerk's user metadata (publicMetadata, privateMetadata, unsafeMetadata), and what reads it. Settings, roles and flags stored there do not come along with the account. Give each one a column or a table in your own database before the cutover, and export the values that exist; an app that reads a role from the session claims needs that role somewhere it can still read it. A role fits an additional field on the user with input: false: it rides on the session's user, no request can set it, and your own admin code writes it through the adapter.

Write the result down. It decides the path, and it fills in What breaks at cutover for your app.

A. Clerk export and scriptB. Seed from your own user table
SourceClerk dashboard CSV and the Clerk APIA table in your app holding the Clerk ID and email
PasswordsKept (bcrypt hash and verify)None. Users return by emailed code, a provider, or a password reset
Provider accounts, TOTPMigratedNot migrated. A provider links again by verified email
NeedsCLERK_SECRET_KEY and the exportEmail OTP or password reset turned on, and an email sender

Before You Begin

Before starting the migration process, set up Entro Auth in your project. Follow the installation guide to get started.

Connect to your database

You'll need to connect to your database to migrate the users and accounts. You can use any database you want, but for this example, we'll use PostgreSQL.

npm install pg

And then you can use the following code to connect to your database.

auth.ts
import { Pool } from "pg";

export const auth = entroAuth({
    database: new Pool({ 
        connectionString: process.env.DATABASE_URL 
    }),
})

Enable Email and Password (Optional)

Enable the email and password in your auth config and implement your own logic for sending verification emails, reset password emails, etc.

Note

Important for Clerk Migrations: Clerk uses bcrypt to hash passwords, while Entro Auth uses scrypt by default. To ensure migrated users can sign in with their existing passwords, you'll need to configure Entro Auth to use bcrypt for password verification.

First, install bcrypt:

npm install pnpm add bcrypt
pnpm add -D @types/bcrypt

Then configure Entro Auth to use bcrypt:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import bcrypt from "bcrypt";

export const auth = entroAuth({
    emailAndPassword: { 
        enabled: true,
        password: { 
            hash: async (password) => { 
                return await bcrypt.hash(password, 10); 
            },
            verify: async ({ hash, password }) => { 
                return await bcrypt.compare(password, hash); 
            },
        },
    },
})

See Email and Password for more configuration options.

Setup Social Providers (Optional)

Add social providers you have enabled in your Clerk project in your auth config.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
    database: new Pool({ 
        connectionString: process.env.DATABASE_URL 
    }),
    emailAndPassword: { 
        enabled: true,
    },
    socialProviders: { 
        github: { 
            clientId: process.env.GITHUB_CLIENT_ID,
            clientSecret: process.env.GITHUB_CLIENT_SECRET,
        } 
    } 
})

Add Plugins (Optional)

You can add the following plugins to your auth config based on your needs.

Admin Plugin will allow you to manage users, user impersonations and app level roles and permissions.

Two Factor Plugin will allow you to add two-factor authentication to your application.

Phone Number Plugin will allow you to add phone number authentication to your application.

Username Plugin will allow you to add username authentication to your application.

auth.ts
import { Pool } from "pg";
import { entroAuth } from "@entro314labs/entro-auth";
import { admin, twoFactor, phoneNumber, username } from "@entro314labs/entro-auth/plugins";
import bcrypt from "bcrypt";

export const auth = entroAuth({
    database: new Pool({ 
        connectionString: process.env.DATABASE_URL 
    }),
    emailAndPassword: { 
        enabled: true,
        password: {
            hash: async (password) => {
                return await bcrypt.hash(password, 10);
            },
            verify: async ({ hash, password }) => {
                return await bcrypt.compare(password, hash);
            },
        },
    },
    socialProviders: {
        github: {
            clientId: process.env.GITHUB_CLIENT_ID!,
            clientSecret: process.env.GITHUB_CLIENT_SECRET!,
        }
    },
    plugins: [admin(), twoFactor(), phoneNumber(), username()],
})

Generate Schema

If you're using a custom database adapter, generate the schema:

npx @entro314labs/entro-auth-cli@latest generate

or if you're using the default adapter, you can use the following command:

npx @entro314labs/entro-auth-cli@latest migrate

Include every plugin you will ship before you generate or migrate, and before any import.

Export Clerk Users

Go to the Clerk dashboard and export the users. It will download a CSV file with the users data. You need to save it as exported_users.csv and put it in the root of your project.

The export includes each user's TOTP secret but not their backup codes, so the migration script generates new backup codes.

Create the migration script

Install a CSV parser to read the export:

npm install csv-parse

Create a new file called migrate-clerk.ts in the scripts folder and add the following code:

scripts/migrate-clerk.ts
import { parse } from "csv-parse/sync";
import { generateRandomString, symmetricEncrypt } from "@entro314labs/entro-auth/crypto";
import type { SecretConfig } from "@entro314labs/entro-auth/crypto";

import { auth } from "@/lib/auth"; // import your auth instance

function getCSVData(csv: string) {
  return parse(csv, {
      columns: true,
      skip_empty_lines: true,
  }) as Array<{
      id: string;
      first_name: string;
      last_name: string;
      username: string;
      primary_email_address: string;
      primary_phone_number: string;
      verified_email_addresses: string;
      unverified_email_addresses: string;
      verified_phone_numbers: string;
      unverified_phone_numbers: string;
      totp_secret: string;
      password_digest: string;
      password_hasher: string;
  }>;
}

const exportedUserCSV = await Bun.file("exported_users.csv").text(); // this is the file you downloaded from Clerk

async function getClerkUsers(totalUsers: number) {
  const clerkUsers: {
      id: string;
      first_name: string;
      last_name: string;
      username: string;
      image_url: string;
      password_enabled: boolean;
      two_factor_enabled: boolean;
      totp_enabled: boolean;
      backup_code_enabled: boolean;
      banned: boolean;
      locked: boolean;
      lockout_expires_in_seconds: number;
      created_at: number;
      updated_at: number;
      external_accounts: {
          id: string;
          provider: string;
          identification_id: string;
          provider_user_id: string;
          approved_scopes: string;
          email_address: string;
          first_name: string;
          last_name: string;
          image_url: string;
          created_at: number;
          updated_at: number;
      }[]
  }[] = [];
  for (let i = 0; i < totalUsers; i += 500) {
      const response = await fetch(`https://api.clerk.com/v1/users?offset=${i}&limit=${500}`, {
          headers: {
              'Authorization': `Bearer ${process.env.CLERK_SECRET_KEY}`
          }
      });
      if (!response.ok) {
          throw new Error(`Failed to fetch users: ${response.statusText}`);
      }
      const clerkUsersData = await response.json();
      clerkUsers.push(...clerkUsersData as any);
  }
  return clerkUsers;
}


export async function generateBackupCodes(
  key: string | SecretConfig,
) {
  const backupCodes = Array.from({ length: 10 })
      .fill(null)
      .map(() => generateRandomString(10, "a-z", "0-9", "A-Z"))
      .map((code) => `${code.slice(0, 5)}-${code.slice(5)}`);
  const encCodes = await symmetricEncrypt({
      data: JSON.stringify(backupCodes),
      key: key,
  });
  return encCodes
}

// Helper function to safely convert timestamp to Date
function safeDateConversion(timestamp?: number): Date {
  if (!timestamp) return new Date();

  const date = new Date(timestamp);

  // Check if the date is valid
  if (isNaN(date.getTime())) {
      console.warn(`Invalid timestamp: ${timestamp}, falling back to current date`);
      return new Date();
  }

  // Check for unreasonable dates (before 2000 or after 2100)
  const year = date.getFullYear();
  if (year < 2000 || year > 2100) {
      console.warn(`Suspicious date year: ${year}, falling back to current date`);
      return new Date();
  }

  return date;
}

// Clerk exports every verified address in one cell. Check the separator in
// your own export; this splits on the common ones.
function isVerified(email: string, verifiedEmailAddresses: string) {
  return verifiedEmailAddresses
      .split(/[\s,;|"[\]]+/)
      .some((address) => address.toLowerCase() === email);
}

async function migrateFromClerk() {
  const jsonData = getCSVData(exportedUserCSV);
  const clerkUsers = await getClerkUsers(jsonData.length);
  const ctx = await auth.$context
  const isAdminEnabled = ctx.options?.plugins?.find(plugin => plugin.id === "admin");
  const isTwoFactorEnabled = ctx.options?.plugins?.find(plugin => plugin.id === "two-factor");
  const isUsernameEnabled = ctx.options?.plugins?.find(plugin => plugin.id === "username");
  const isPhoneNumberEnabled = ctx.options?.plugins?.find(plugin => plugin.id === "phone-number");
  for (const user of jsonData) {
      const { id, first_name, last_name, username, primary_email_address, primary_phone_number, verified_email_addresses, unverified_email_addresses, verified_phone_numbers, unverified_phone_numbers, totp_secret, password_digest, password_hasher } = user;
      const clerkUser = clerkUsers.find(clerkUser => clerkUser?.id === id);
      // Entro Auth looks users up by the lowercased address
      const email = primary_email_address.toLowerCase();

      // Skip users a previous run already migrated, so the script can be re-run
      const existingUser = await ctx.adapter.findOne<{
          id: string;
      }>({
          model: "user",
          where: [{
              field: "id",
              value: id
          }]
      });
      if (existingUser) {
          console.log(`Skipping ${id}: already migrated`);
          continue;
      }

      // Write each user and their accounts together. Only atomic where the adapter has transactions on.
      await ctx.adapter.transaction(async (trx) => {
          // create user
          const createdUser = await trx.create<{
              id: string;
          }>({
              model: "user",
              data: {
                  id,
                  email,
                  // Only the address being stored counts, not any other verified address
                  emailVerified: isVerified(email, verified_email_addresses),
                  name: `${first_name} ${last_name}`,
                  image: clerkUser?.image_url,
                  createdAt: safeDateConversion(clerkUser?.created_at),
                  updatedAt: safeDateConversion(clerkUser?.updated_at),
                  // # Two Factor (if you enabled two factor plugin)
                  ...(isTwoFactorEnabled ? {
                      twoFactorEnabled: Boolean(totp_secret)
                  } : {}),
                  // # Admin (if you enabled admin plugin)
                  ...(isAdminEnabled ? {
                      banned: clerkUser?.banned,
                      banExpires: clerkUser?.lockout_expires_in_seconds
                         ? new Date(Date.now() + clerkUser.lockout_expires_in_seconds * 1000)
                         : undefined,
                      role: "user"
                  } : {}),
                  // # Username (if you enabled username plugin)
                  ...(isUsernameEnabled ? {
                      // Empty CSV cells parse as empty strings
                      username: username || undefined,
                  } : {}),
                  // # Phone Number (if you enabled phone number plugin)  
                  ...(isPhoneNumberEnabled ? {
                      // Empty CSV cells parse as empty strings
                      phoneNumber: primary_phone_number || undefined,
                      phoneNumberVerified: verified_phone_numbers.length > 0,
                  } : {}),
              },
              // keep the Clerk user ID
              forceAllowId: true
          })
          // create credential account
          // Clerk's API lists only OAuth accounts, so passwords come from the export
          if (password_digest) {
              await trx.create({
                  model: "account",
                  data: {
                      providerId: "credential",
                      accountId: createdUser.id,
                      userId: createdUser.id,
                      password: password_digest,
                      createdAt: safeDateConversion(clerkUser?.created_at),
                      updatedAt: safeDateConversion(clerkUser?.updated_at),
                  }
              })
          }
          // create external account
          const externalAccounts = clerkUser?.external_accounts;
          if (externalAccounts) {
              for (const externalAccount of externalAccounts) {
                  const { id, provider, identification_id, provider_user_id, approved_scopes, email_address, first_name, last_name, image_url, created_at, updated_at } = externalAccount;
                  const providerId = provider.replace("oauth_", "");
                  await trx.create({
                      model: "account",
                      data: {
                          id,
                          providerId,
                          accountId: externalAccount.provider_user_id,
                          scope: approved_scopes,
                          userId: createdUser.id,
                          createdAt: safeDateConversion(created_at),
                          updatedAt: safeDateConversion(updated_at),
                      },
                      forceAllowId: true
                  })
              }
          }

          //two factor
          if (isTwoFactorEnabled && totp_secret) {
              await trx.create({
                  model: "twoFactor",
                  data: {
                      userId: createdUser.id,
                      // Clerk exports Base32 secrets, so mark them for decoding.
                      // Run the script with the secret production uses, or these won't decrypt.
                      secret: await symmetricEncrypt({
                          key: ctx.secretConfig,
                          data: `base32:${totp_secret}`,
                      }),
                      backupCodes: await generateBackupCodes(ctx.secretConfig)
                  }
              })
          }
      })
  }
}

migrateFromClerk()
  .then(() => {
      console.log('Migration completed');
      process.exit(0);
  })
  .catch((error) => {
      console.error('Migration failed:', error);
      process.exit(1);
  });

Make sure to replace the process.env.CLERK_SECRET_KEY with your own Clerk secret key. Feel free to customize the script to your needs.

Run the migration

Run the migration:

bun run scripts/migrate-clerk.ts # you can use any thing you like to run the script
Warning

Make sure to:

  1. Test the migration in a development environment first
  2. Monitor the migration process for any errors
  3. Verify the migrated data in Entro Auth before proceeding
  4. Keep Clerk installed and configured until the migration is complete

Before you run it against production:

  • Use the production secret. The script encrypts TOTP secrets and backup codes with ctx.secretConfig, which comes from the secret option or ENTRO_AUTH_SECRET (or ENTRO_AUTH_SECRETS). Run it with the same secret configuration production uses, or migrated TOTP and backup codes will not decrypt.
  • Check the hasher. The script reads password_hasher but does not check it. Confirm it is bcrypt for every row before storing password_digest, and skip or flag rows that use another hasher.
  • Re-running. The script skips a user whose id already exists, so you can run it again after a partial failure. It writes each user and their accounts in one transaction call. With the built-in adapter on a pg Pool, as in this guide, that is a database transaction. An adapter without transaction support, or with its transaction option off, runs the writes one after another, so a user that failed partway is skipped on the next run without their accounts. Check your adapter; if it has no transactions, delete such a user before re-running, or restore the backup and run again from the start.
  • Unverified users. A user whose primary address is not among the Clerk export's verified addresses is created with emailVerified: false. If they later sign in with an emailed code or a magic link, Entro Auth deletes their accounts (the migrated password and provider links) and their sessions before marking the address verified. See Why emailVerified matters. Tell those users, or leave them out.

Verify the migration

After running the migration, verify that all users have been properly migrated by checking the database.

Update your components

Now that the data is migrated, you can start updating your components to use Entro Auth. Here's an example for the sign-in component:

components/auth/sign-in.tsx
import { authClient } from "@/lib/auth-client";

export const SignIn = () => {
  const handleSignIn = async () => {
    const { data, error } = await authClient.signIn.email({
      email: "user@example.com",
      password: "password",
    });
    
    if (error) {
      console.error(error);
      return;
    }
    // Handle successful sign in
  };

  return (
    <form onSubmit={handleSignIn}>
      <button type="submit">Sign in</button>
    </form>
  );
};

Update the middleware

Replace your Clerk middleware with Entro Auth's middleware:

middleware.ts

import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "@entro314labs/entro-auth/cookies";
export async function middleware(request: NextRequest) {
  const sessionCookie = getSessionCookie(request);
  const { pathname } = request.nextUrl;
  if (sessionCookie && ["/login", "/signup"].includes(pathname)) {
    return NextResponse.redirect(new URL("/dashboard", request.url));
  }
  if (!sessionCookie && pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard", "/login", "/signup"],
};

Remove Clerk Dependencies

Once you've verified that everything is working correctly with Entro Auth, you can remove Clerk:

Remove Clerk
pnpm remove @clerk/nextjs @clerk/themes @clerk/types

Seed users from your own user table

Use this path when your app already keeps a table with each user's Clerk ID and email, for example a profile table filled from Clerk webhooks or on first sign-in. It carries over no passwords and no provider accounts. Users come back by:

  • An emailed code. The Email OTP plugin finds the user by email and signs them into the existing ID. Set disableSignUp: true if new users must not sign up by code; a carried-over user is found by email either way.
  • A provider. The provider account is linked to the existing user by email, under the conditions in Why emailVerified matters.
  • A password reset. requestPasswordReset (with emailAndPassword.sendResetPassword configured) sends the reset to a user who has no password, and completing the reset creates their credential account.

Turn on a way back in

For example, email OTP:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { emailOTP } from "@entro314labs/entro-auth/plugins";

export const auth = entroAuth({
    plugins: [
        emailOTP({
            disableSignUp: true, // only users who already exist can sign in by code
            async sendVerificationOTP({ email, otp, type }) {
                // send the code with your email provider
            },
        }),
    ],
})

Apply the schema with every plugin you will ship (see Generate Schema). Note the table and column names it produced: the default user table requires id, name, email (unique), emailVerified, createdAt and updatedAt. A custom modelName or fields, or a non-default Postgres schema, changes the names in the SQL below.

Seed the users

Seed only the users Clerk still has. A table your app fills from webhooks can hold rows whose Clerk user was deleted without the row going with it (a webhook that failed, a user removed in the dashboard). Clerk does not let that person in today, and a seeded user row would: they could sign in by emailed code. Compare the table with Clerk's own list first (GET /v1/users), seed the ids that are in both, and take the email from Clerk where the two differ.

This Postgres example gives each profile a user row whose id is the Clerk ID the profile already holds. Replace public.user_profiles, clerk_user_id, email, clerk_email_verified and created_at with your own names.

seed-users.sql
-- Idempotent: rows that already exist, by id or by email, are left alone.
insert into "user" ("id", "name", "email", "emailVerified", "createdAt", "updatedAt")
select
  p.clerk_user_id,
  '',
  lower(p.email),
  -- true only where Clerk verified this exact address
  coalesce(p.clerk_email_verified, false),
  p.created_at,
  now()
from public.user_profiles p
where coalesce(p.email, '') <> ''
  and not exists (select 1 from "user" u where u."id" = p.clerk_user_id)
  and not exists (select 1 from "user" u where u."email" = lower(p.email))
on conflict do nothing;
  • name is required. An empty string is what the email OTP plugin itself writes for a new user without a name; use a real name column if you have one.
  • Lowercase the email (see Keep the Clerk user ID). Whether Clerk ever stores mixed case is not confirmed; lowercase anyway.
  • Two profiles whose emails differ only by case collapse to one user, and the second profile is left without a user row. The check below finds it.
  • Put the block in the same migration file the deploy applies, so the rehearsal and production run the same text. Running it twice must insert nothing the second time.

Check the result

check-seed.sql
-- Must return 0: profiles with an email but no user row under their Clerk ID.
select count(*) from public.user_profiles p
where coalesce(p.email, '') <> ''
  and not exists (select 1 from "user" u where u."id" = p.clerk_user_id);

-- Must return 0: users whose stored email is not lowercase.
select count(*) from "user" where "email" <> lower("email");

Compare the total counts of profiles and users before and after. Then sign in once by each method and check that the session's user.id equals the profile's Clerk ID.

Why emailVerified matters

When someone signs in with a provider whose email matches an existing user that has no account for that provider, Entro Auth links the provider to that user only when all of these hold:

  • the provider says the email is verified, or the provider is in account.accountLinking.trustedProviders;
  • the existing user's emailVerified is true, unless account.accountLinking.requireLocalEmailVerified is false (the default is true; keep it);
  • accountLinking.enabled is not false and accountLinking.disableImplicitLinking is not true.

Otherwise the sign-in fails with account_not_linked. trustedProviders only waives the provider-side check, never the local one. So a carried-over user seeded with emailVerified: false cannot come back through a provider until they verify the address, for example with an emailed code. See Account Linking.

With the Two Factor plugin, a provider sign-in held to the second step does not link a provider to an account that has 2FA on; it is refused with PROVIDER_NOT_LINKED. Handle both codes on your error page.

Set emailVerified to true only for the exact address Clerk verified. If you mark an address verified that Clerk never verified, whoever registered it keeps the account, and the real owner's later provider sign-in with that address is linked into it.

Warning

When a user with emailVerified: false signs in with an emailed code (email OTP) or a magic link, Entro Auth first deletes all of that user's accounts and sessions, then marks the address verified. Path B seeds no accounts, so nothing is lost there. A path A user created unverified loses the migrated password and provider links, and any sessions created since the migration.

Note

Not tested: users who signed in to Clerk with Apple and chose "Hide My Email". Apple gives a private relay address, which will not match a carried-over email, so the sign-in will not find the migrated account: with disableImplicitSignUp it is refused, and without it a new, empty account is created. Check this before telling users that Apple brings them back to their old account.

Cutover

The order below matters. Every command is an example, and none of these commands or flags is confirmed in Entro Auth; check them against your tools before relying on them. Use your host's and your database's equivalents, with client tools of your production Postgres major version. Never print connection strings or secret values in a terminal, a log or a chat; read them from your host's environment or a secret manager. Rehearsal and local testing need their own database, ENTRO_AUTH_SECRET and `ENTRO_AUTH_URL. Check that no local env file points at the production database before running anything.

Before the day:

  • The assessment is done and What breaks at cutover is filled in for your app.
  • Native builds that sign in with Entro Auth are released and adopted, if your app has them.
  • Every user has a way back in: email OTP or password reset with a working email sender, and providers configured on the production domain.
  • Release notes say that everyone is signed out and that OAuth and MCP connections must be reconnected.

Freeze and check out

Stop other commits to the branch. Merge, then deploy from a clean checkout of the merged commit, not a working tree with other edits:

Terminal
git worktree add --detach ../cutover <merged-commit>

Copy your host's project metadata into it if the deploy needs it.

Back up production

Take a backup and keep one copy off the machine, in private storage you control:

Terminal
pg_dump --format=custom --file=prod-before-cutover.dump "$DATABASE_URL"

Rehearse on a restored copy

Restore the backup into a database of the same Postgres major version and apply the schema there:

Terminal
pg_restore --no-owner --dbname="$REHEARSAL_URL" prod-before-cutover.dump
psql "$REHEARSAL_URL" -v ON_ERROR_STOP=1 --single-transaction -f schema.sql
  • Run the carryover there: the path A script pointed at the copy, or the path B SQL.
  • Compare row counts before and after, and run the orphan check from Check the result.
  • Run the previous build against the upgraded copy. Rolling back by promoting the previous deployment only works if the schema change is additive and the old code still runs on it.
  • A database with extensions (for example vector) restored into a stock image reports errors for them. Read them; don't ignore other errors.

Set production environment variables

Set them in your host, not in a file in the repository:

  • ENTRO_AUTH_SECRET: new and random, never the development value. Generate one with npx @entro314labs/entro-auth-cli@latest secret. Path A encrypts TOTP secrets with it, so set it before running the script.
  • ENTRO_AUTH_URL: the production origin.
  • Provider client IDs and secrets, and your email sender's credentials.

Leave the Clerk variables in place for now.

Apply the schema before the code

Apply the schema before deploying code that expects it:

Terminal
psql "$DIRECT_URL" -v ON_ERROR_STOP=1 --single-transaction -f schema.sql

Or run npx @entro314labs/entro-auth-cli@latest migrate with production environment variables, if that is how your app manages its schema. Deploying first gives errors until the schema lands.

Run the carryover

Path B: run the seed SQL, unless it is already in the schema file you applied. Path A: run the script once against production. Then check the counts and run the orphan check.

Deploy once

Deploy once, from the clean checkout, and wait for it to finish. Don't run the deploy command again while one is in progress. For example, on Vercel:

Terminal
vercel deploy --prod

Health check and real sign-ins

Hit your app's health endpoint. Then complete one real sign-in per method: an emailed code (proves delivery), each provider (proves the token exchange), and a password if you took path A. A provider's sign-in page opening is not proof; only a completed sign-in is. Check that the signed-in user sees their own data under their Clerk ID.

Catch late sign-ups

Users may have signed up through Clerk between the backup and the deploy. Path B: run the seed and the orphan check again. Path A: compare the Clerk user count with your export and import the difference.

Disable the Clerk webhook

If you removed the webhook route, disable the endpoint in the Clerk dashboard.

Keep a rollback window

Keep the previous deployment ready to promote (on Vercel, for example, vercel promote <previous-deployment-url>). Promotion does not undo schema changes or rows; restore the backup only if the data itself is wrong.

After the window, remove the Clerk environment variables from your host, remove the Clerk packages and the webhook route, and rotate any credential that was exposed during the move.

What breaks at cutover

WhatEffectWhat to doStatus
Released native builds that sign in with ClerkEvery API call gets a 401Ship the native build that signs in with Entro Auth firstExpected, not observed in testing
OAuth or MCP clients authorized through ClerkTheir tokens stop workingUsers reconnect; say so in release notesExpected, not observed in testing
The Clerk webhook endpointClerk gets 404s once the route is removedDisable the endpoint in ClerkExpected, not observed in testing
Active web sessionsEveryone is signed outExpected; say so in release notesAlways
Path A users created with emailVerified: falseAn emailed-code or magic-link sign-in deletes their migrated password, provider links and sessionsTell them, or leave them outFollows from the code
Apple "Hide My Email" usersThe relay address does not match the carried-over emailCheck before relying on Apple to bring users backNot tested
A provider sign-in to an account with 2FA onRefused with PROVIDER_NOT_LINKEDSign in another way, pass the second step, then linkSocialDocumented
Route handlers guarded by one redirecting checkA signed-out fetch follows the redirect and receives the sign-in page's HTML with a 200Answer 401 from route handlers; redirect only from pagesObserved
Sign-up that Clerk restrictedAn emailed code or a provider sign-in makes an account for anyoneSet disableSignUp on each method before the deployFollows from the code
Second verified email addressesNot carried over; a check made against one stops passingSettle which address the account keeps; say soObserved
Profile images served by ClerkStop loading once the Clerk application is deletedCopy them to your own storage first, or drop themExpected, not observed in testing

Additional Resources

Goodbye Clerk, Hello Entro Auth – Full Migration Guide!

Wrapping Up

Congratulations! You've successfully migrated from Clerk to Entro Auth.

Entro Auth offers greater flexibility and more features—be sure to explore the documentation to unlock its full potential.