Skip to content

From Clerk

For: an operator and a developer who move an app from Clerk to authtempo.

What it does: you join two exports of Clerk, import them into core’s tables, and change the app’s Clerk calls to @authtempo/client.

  • An API with authtempo and password set. Do a getting started tutorial first.
  • The user export CSV of the Clerk dashboard, from Settings and User exports. It holds the password digests. The command reads it.
  • A secret key of Clerk, for GET /v1/users. The command reads the users that it fetches.
  • @authtempo/cli and @authtempo/legacy-hashes in the app’s workspace. authtempo import is a command of the first.
  1. Download the user export CSV from the Clerk dashboard as export.csv.
  2. Save the script below as clerk-export.sh in a folder that only you can read. It fetches every page of GET /v1/users, and joins the pages into one array.
  3. Run it with bash clerk-export.sh. Do not paste it into a shell: set -e closes that shell at the first error.
  4. The script stops at the first failed call. curl prints the HTTP error, such as 401 for a wrong key.
  5. A failed run writes no new file and keeps the old users.json. Run the script again. A complete run writes users.json.
clerk-export.sh
set -euo pipefail
umask 077
# Every page goes to a temporary folder first. Only a complete run moves users.json here.
t=$(mktemp -d)
trap 'rm -rf "$t"' EXIT
o=0; : > "$t/pages.ndjson"
while :; do
page=$(curl -sSf -H "Authorization: Bearer $CLERK_SECRET_KEY" "https://api.clerk.com/v1/users?limit=500&offset=$o")
[ "$(printf '%s' "$page" | jq length)" -eq 0 ] && break
printf '%s\n' "$page" >> "$t/pages.ndjson"
o=$((o + 500))
done
jq -s 'add // []' "$t/pages.ndjson" > "$t/users.json"
mv "$t/users.json" .
Terminal window
bash clerk-export.sh
  1. For organizations, write organizations.json: an array of GET /v1/organizations objects, each with its memberships array.
  1. Chain the legacy seam before core’s PBKDF2 in the API. Pass ["bcrypt"] as formats.
The API after the import
// The API after the move of the guide "From Clerk".
import {
createAuth,
createPbkdf2PasswordHash,
type MailPort,
type StorageAdapter,
} from "@authtempo/core";
import { createLegacyPasswordHash, type LegacyFormat } from "@authtempo/legacy-hashes";
// Give `authtempo import clerk --formats` exactly this list.
export const CLERK_FORMATS: readonly LegacyFormat[] = ["bcrypt"];
export function createClerkAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string }) {
return createAuth({
baseURL: "https://api.example.com",
trustedOrigins: [],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
password: {
hash: createLegacyPasswordHash({
// Only the formats that the import brought. A row in another format never signs in.
formats: CLERK_FORMATS,
// New hashes, and the rehash at the first right sign-in, are PBKDF2.
next: createPbkdf2PasswordHash(),
}),
},
});
}
  1. Run the import as a dry run, and read the report.
  2. Check the hashes: line against --formats. It counts the hash formats of the export, such as hashes: bcrypt 812, none 31.

The @authtempo packages are on npm. Add the CLI to your app with pnpm add -D @authtempo/cli, and run each command as pnpm exec authtempo ….

Terminal window
authtempo import clerk --csv export.csv --users users.json --organizations organizations.json --formats bcrypt --target postgres --url-env DATABASE_URL --dry-run

Run the real import on a copy of the database only. The one real import into the real database runs at step 9 of The cutover, after the old sign-ins stop. If it runs earlier, a password, an address, or a delete that changes in the old system after it is lost. One real import tells why.

  1. Make the copy. On Postgres, create an empty database, set COPY_URL to its URL, and load the real one into it with pg_dump --no-owner "$DATABASE_URL" | psql "$COPY_URL".
  2. On D1, load the real database into the empty local copy of the import Worker with wrangler d1 export <database> --remote --output copy.sql and wrangler d1 execute <database> --local --file copy.sql.
  3. Run both in the folder of the import Worker. Delete its .wrangler/state first, or the load stops on a table that exists.
  4. Run the same command without --dry-run, with --url-env COPY_URL. On D1, run the import Worker without "remote": true, so it writes the local copy.
Terminal window
authtempo import clerk --csv export.csv --users users.json --organizations organizations.json --formats bcrypt --target postgres --url-env COPY_URL
  1. Run authtempo import verify with the same files on the copy. It exits 0 only when the copy holds the whole export.
  2. Run authtempo check <base url> against the API.
  3. Sign in once with a known user and the old password, and once by each other method of the app. Do it at step 13 of The cutover: before that step, the real database holds no user.
  4. Drop the copy, and on D1 delete copy.sql, when import verify exits 0. The copy holds every user of the export.
Terminal window
authtempo import verify clerk --csv export.csv --users users.json --organizations organizations.json --formats bcrypt --target postgres --url-env COPY_URL
authtempo check https://api.example.com
The test of this guide
import { readFileSync } from "node:fs";
import { importUsers, readSource } from "@authtempo/import";
import { FIXTURE_EXPORTS } from "@authtempo/import/testing";
import { VECTORS } from "@authtempo/legacy-hashes/testing";
import { describe, expect, it } from "vitest";
import { call, harness } from "../support/harness.ts";
import { CLERK_FORMATS, createClerkAuth } from "./clerk.ts";
// The fixture export of the Clerk reader: Kim with the bcrypt2b vector.
const f = FIXTURE_EXPORTS.clerk;
const GUIDE = new URL("../../src/content/docs/docs/migrate/clerk.mdx", import.meta.url);
describe("move users from Clerk", () => {
it("signs an imported user in with the old password and rewrites the hash as PBKDF2", async () => {
const h = harness();
const report = await importUsers(h.storage, await readSource(f.bundle), {
formats: CLERK_FORMATS,
});
expect({ passwords: report.created.password, refused: report.refusedHashes }).toEqual({
passwords: 1,
refused: [],
});
if (f.signIn === null) throw new Error("the fixture names no user that signs in");
const { email, password } = f.signIn;
const auth = createClerkAuth(h);
const signIn = (p: string) =>
call(auth, "POST", "/auth/password/sign-in", { email, password: p });
expect((await signIn(VECTORS.bcrypt2b.wrong)).status).toBe(401);
const first = await signIn(password);
expect(first.status).toBe(200);
const { user } = (await first.json()) as { user: { id: string } };
const row = await h.storage.findOne("password", [
{ field: "userId", op: "eq", value: user.id },
]);
expect(row?.hash.startsWith("pbkdf2-sha256$")).toBe(true);
expect((await signIn(password)).status).toBe(200);
});
it("uses the formats of the fixture", () => {
expect(CLERK_FORMATS).toEqual(f.formats);
});
it("gives the guide the formats of this sample", () => {
const guide = readFileSync(GUIDE, "utf8");
const flags = [...guide.matchAll(/--formats (\S+)/g)].map((m) => m[1]);
expect(flags.length).toBeGreaterThan(0);
for (const list of flags) expect(list).toBe(CLERK_FORMATS.join(","));
const arrays = [...guide.matchAll(/`(\["[^`]*\])`/g)].map((m) => m[1]);
for (const a of arrays) expect(a).toBe(JSON.stringify(CLERK_FORMATS).replaceAll(",", ", "));
});
});
  1. Change each auth call of the app with the table of The calls.
  1. Do the steps of The cutover.
Clerk authtempo
signIn.create({ identifier, password }) client.password.signIn({ email, password })
signUp.create({ emailAddress, password }) client.password.signUp({ email, password })
signIn.authenticateWithRedirect({ strategy: "oauth_google" }) Send the browser to /auth/social/google/start?next=/ on the API.
clerk.signOut() client.signOut()
useUser(), useAuth() client.session()
getToken() client.jwt.token()
auth() on the server auth.session(request)
useOrganizationList() client.organizations.list()
organization.inviteMember({ emailAddress, role }) client.organizations.invitations.invite({ organizationId, email, role })
  • A user in one file and not in the other is listed as unmatched_row. An id that one file holds twice is listed as duplicate_row, and no copy imports.
  • Only a password_hasher of bcrypt imports. Any other hasher is refused by its name.
  • The role org:admin becomes owner.
  • The strategy oauth_github imports as GitHub, and oauth_linkedin_oidc as LinkedIn. The older oauth_linkedin is listed as identity:linkedin_legacy.
  • A user with a banned value other than false is skipped.
  • Clerk passkeys do not move: the API gives no public key.
  • The command exits 1: read the report for unmatched_row, duplicate_row, no_source_id, or a refused hash. The exit status lists each.
  • The command stops at start: organizations.json is not a JSON array.
  • invalid_credentials: the password is wrong, or the user imported with no password.