Skip to main content

Migrate from Auth.js to Clerk

This guide shows how to migrate an application using Auth.js (formerly NextAuth.js) to use Clerk for authentication.

Install @clerk/nextjs

Clerk's Next.js SDK gives you access to prebuilt components, hooksNext.js Icon, and helpersNext.js Icon for Next.js Server Components, Route Handlers and Middleware. Run the following command to install it:

npm install @clerk/nextjs
pnpm add @clerk/nextjs
yarn add @clerk/nextjs
bun add @clerk/nextjs

Set environment variables

Add the following code to your .env file to set your and .

.env
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY
CLERK_SECRET_KEY=YOUR_SECRET_KEY

Wrap your Next.js app in <ClerkProvider>

Remove the <SessionProvider session={session}> provider from Auth.js and replace it with <ClerkProvider>.

The <ClerkProvider> component provides session and user context to Clerk's hooks and components. It's recommended to wrap your entire app at the entry point with <ClerkProvider> to make authentication globally accessible. See the reference docs for other configuration options.

app/layout.tsx
import { ClerkProvider } from '@clerk/nextjs'
import './globals.css'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ClerkProvider>{children}</ClerkProvider>
      </body>
    </html>
  )
}
pages/_app.tsx
import '@/styles/globals.css'
import { ClerkProvider } from '@clerk/nextjs'
import type { AppProps } from 'next/app'
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ClerkProvider {...pageProps}>
      <Component {...pageProps} />
    </ClerkProvider>
  )
}
export default MyApp

Set up sign-up and sign-in UI

Account Portal

Clerk's Account Portal hosts the <SignIn />, <SignUp />, <UserProfile />, and other components for your application. Read more about Account Portal.

To use the Account Portal, remove the routes that mount the Auth.js sign-in and sign-up UI. Replace the links to those routes with the <SignInButton> or <SignUpButton> components.

Self-hosted UI

If Clerk's Account Portal pages aren't a good fit for your app, you can build a custom sign-in and sign-up UI in one of two ways:

Protect your app

You can control access in two ways: protect your whole app or specific routes with Clerk Middleware, or show and hide UI with Clerk's components based on whether the user is signed in.

Control access to your app with Clerk Middleware

You will need to remove the Auth.js Middleware from your application, and replace it with Clerk's Middleware helper, clerkMiddleware().

Auth.js's middleware always rejects unauthorized requests. You may have additionally configured the Next.js middleware config to protect specific private routes. You will need to make note of this configuration so you can recreate it.

By default, Clerk's Middleware runs for your entire application.

The example below is a basic configuration that does not protect any routes. All routes are public and you must opt-in to protection for routes. Read the clerkMiddleware()Next.js Icon documentation to learn more about how you can configure your Middleware.

Important

If you're using Next.js ≤15, name your file middleware.ts instead of proxy.ts. The code itself remains the same; only the filename changes.

proxy.ts
import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware()

export const config = {
  matcher: [
    '/((?!.*\\..*|_next).*)', // Don't run middleware on static files
    '/', // Run middleware on index page
    '/(api|trpc)(.*)', // Run middleware on API routes
    '/__clerk/(.*)', // Run middleware on Clerk frontend API routes
  ],
}

Control access to your app with Clerk's components

To conditionally render UI when the user is signed in, wrap it with <Show when="signed-in">.

To conditionally render UI when the user is not signed in, wrap it with <Show when="signed-out">.

app/page.tsx
import { Show } from '@clerk/nextjs'
import { Suspense } from 'react'

export default function Home() {
  return (
    <div>
      <Suspense>
        <Show when="signed-out">
          <p>This content is public. Only signed out users can see this.</p>
        </Show>
        <Show when="signed-in">
          <p>This content is private. Only signed in users can see this.</p>
        </Show>
      </Suspense>
    </div>
  )
}

Read user and session data

Server-side

Replace any Auth.js getServerSession(req, res, authOptions) with Clerk's helpers.

Replace Auth.js's getServerSession() with Clerk's auth()Next.js Icon helper to read your user data.

app/page.tsx
import { auth } from '@clerk/nextjs/server'
import { Suspense } from 'react'

export default function Page() {
  return (
    <Suspense>
      <Home />
    </Suspense>
  )
}

async function Home() {
  const { userId } = await auth()
  console.log(userId)

  return <p>Home Page</p>
}

Replace Auth.js's getServerSession() with Clerk's getAuth()Next.js Icon helper to read your user data.

pages/index.tsx
import { getAuth, buildClerkProps } from '@clerk/nextjs/server'
import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const { userId } = getAuth(ctx.req)
  console.log(userId)

  return { props: { ...buildClerkProps(ctx.req) } }
}

Client-side

Replace Auth.js's useSession() hook with Clerk's hooks.

The useAuth() hook can be used to retrieve basic authentication information. The useUser() hook can be used to retrieve the full User object, which includes information about the user, such as their first name, emails, phone numbers, and more.

app/page.tsx
'use client'
import { useAuth, useUser } from '@clerk/nextjs'

export default function Home() {
  const { userId, sessionId } = useAuth()
  const { isSignedIn, user } = useUser()
  console.log(userId, sessionId, isSignedIn, user)

  return <p>Home Page</p>
}

User IDs as foreign keys

If your database uses the Auth.js userId as a foreign key, you have two options:

Use Clerk's externalId field

When you migrate user data from Auth.js to Clerk, Clerk generates new user IDs for each user. If you are using existing user IDs as foreign keys in your database (e.g., in a user_id column), you can save those IDs as the user's externalId in Clerk. This externalId can be included in the by adding the following customization. The following example will set the user's ID to be externalId if one is present, otherwise, it will use the Clerk's user ID.

{
  "userId": "{{user.external_id || user.id}}"
}

To access the userId from the session claims, you can use the auth() helper.

app/page.tsx
import { auth } from '@clerk/nextjs/server'
import { Suspense } from 'react'

export default function Page() {
  return (
    <Suspense>
      <Welcome />
    </Suspense>
  )
}

async function Welcome() {
  const { sessionClaims } = await auth()

  if (!sessionClaims) {
    return <p>Not signed in</p>
  }

  const userId = sessionClaims.userId

  return <p>Welcome user {userId}</p>
}

To access the userId from the session claims, you can use the getAuth() helper.

pages/index.tsx
import { getAuth, buildClerkProps } from '@clerk/nextjs/server'
import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const { isAuthenticated, sessionClaims } = getAuth(ctx.req)

  if (!isAuthenticated) {
    return { props: { ...buildClerkProps(ctx.req) } }
  }

  const userId = sessionClaims.userId
  console.log(userId)

  return { props: { ...buildClerkProps(ctx.req) } }
}

Note

You can't read this claim on the client. If you use one of Clerk's hooks, check whether externalId exists. If it doesn't, read userId.

Update your database

After the data migration, update the foreign keys in your database to the new Clerk user IDs if you prefer to replace the Auth.js IDs.

To keep referencing users by their existing IDs, see foreign keys.

Create a Clerk production instance

Every Clerk application has a Development and a Production instance. Before you start migrating user data, you need to configure your Clerk Production instance and migrate your Auth.js users directly into that instance. The Deploying to Production page covers creating a Production instance.

To test the migration or set up staging, import a small set of users into the Development instance first.

Migrate user data from Auth.js to Clerk

The Clerk CLI exports your users from your Auth.js database with clerk migrate export authjs, then creates them in Clerk with clerk migrate import.

To retain the user data in your database for easy querying, see the guide on data synchronization with webhooks.

Migrate with an AI agent

If you work with an AI coding agent, the clerk-migrate skill can run your migration for you with the Clerk CLI. Install Clerk's skills:

terminal
npx skills add clerk/skills

Then ask your agent to migrate your users to Clerk. The skill exports your users, runs a dry run against your instance, and shows you what it found. It imports only after you approve.

What you need

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:

terminal
npm install -g clerk
clerk auth login
clerk link

To 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.

Warning

New development instances have a limit of 100 users. Production instances have no user limit. Before creating users, the import checks a development instance's count against its limit and rejects the users past it. To rehearse with a larger export, import into development with --allow-partial, check the result, undo the run, then import everyone into production. See instance user limits for the commands, overrides, and fallback behavior.

What migrates

  • Auth.js IDs: Each user's id becomes the Clerk user's external_id.
  • Names: name becomes firstName and lastName. The source uses a one-word name as the first name, unless it matches the user's own email address. In that case, the source omits it.
  • Unverified emails: They stay unverified by default. Auth.js records email verification as a nullable timestamp. The import attaches an address with no emailVerified value as unverified and keeps it off the primary fields. The checks reject a user whose only email is unverified when your instance requires an email. Auth.js leaves an OAuth user's email unverified, and the export warns when it finds any. If every provider you use verifies addresses, pass --trust-oauth-emails to the export to mark those emails verified. To reserve unverified addresses instead, see unverified emails and phones.

What doesn't migrate

  • Passwords: Auth.js core stores no passwords. Its users sign in with OAuth or email links, so they arrive without credentials.

    If your app also uses the Credentials provider, those passwords live in your app's own tables, and the export doesn't read them. Add them to the file yourself, as in import a file you exported yourself, or have those users reset their password.

  • Social accounts: Enable the same providers on the SSO connections page in the Clerk Dashboard. When a user signs in with one, Clerk links it to their imported account by verified email address. Clerk doesn't link to an address the import attached as unverified, so that sign-in creates a separate user. To link those users, import with --reserve-unverified. If you reserve the address and the provider doesn't confirm it, Clerk asks the user to verify it before linking. See account linking.

Export your users from your Auth.js database

Run the export, and enter your database's connection string when the CLI asks:

terminal
clerk migrate export authjs

Enter a Postgres, MySQL, or libsql/Turso connection string, such as postgres://<user>:<password>@<host>:5432/<database>. For libsql/Turso (libsql://…), include the token in ?authToken= or set TURSO_AUTH_TOKEN or LIBSQL_AUTH_TOKEN.

For SQLite, pass the file path with --db-url. The path has to start with file: or ./, or end in .sqlite, .sqlite3, or .db.

Without --db-url, the CLI reads AUTHJS_DB_URL, then prompts for it. The prompt masks what you type, and a value entered at a prompt stays out of your shell history. If the database rejects the connection string, the prompt explains why and asks again. With --yes, --json, in an agent run, or without a terminal, the export doesn't prompt, and fails if the connection string is missing or rejected.

Prisma capitalizes the Auth.js user table, and Drizzle doesn't. The export tries next_auth.users (the Supabase adapter's table, on Postgres only), User, user, then users, and reports which table it found. It also reads the legacy NextAuth email_verified and created_at columns when that's the shape it finds.

It saves your users as export.json in a new run, and prints the run ID and a field coverage table:

Field coverage
  ✓ 240/240 have an email address
  ! 198/240 have a verified email
  ! 176/240 have a name

Pass -o <path> to write the file somewhere else. The path has to end in .json.

Import your users into Clerk

With --app or a linked project, the import targets development by default. For production, add --instance prod to the dry-run command and keep it when you import. With a Secret Key, use the production instance's key instead.

Check the export against your Clerk instance first. A dry run writes nothing and skips the import's consent, legal acceptance, and reservation questions, so add --skip-legal-checks to preview importing users without legal acceptance, or --reserve-unverified to preview reserving unverified emails and phones:

terminal
clerk migrate import <export_run_id> --dry-run

The export recorded its source, so the import needs no --source. If the checks reject a user, fix the file or instance, or pass --allow-partial to import the users that pass. See check before you import.

After the checks pass, rerun the same command with --yes instead of --dry-run, keeping the input and other flags. Leave off --yes to confirm at a prompt.

Use the import run's ID to check its results or undo it. To continue an interrupted import, run the same command again.

Import a file you exported yourself

To import users from an API response or database export, save them as users.json in the following format:

users.json
[
  {
    "userId": "string",
    "email": "email",
    "email_verified": "timestamp (optional)",
    "created_at": "timestamp (optional)",
    "firstName": "string (optional)",
    "lastName": "string (optional)",
    "password": "string (optional)",
    "passwordHasher": "string (required whenever password is set)"
  }
]

Then run clerk migrate import users.json --source authjs.

For the accepted passwordHasher values, see password_hasher in the CreateUser Backend API reference. The CLI rejects unsupported passwordHasher values before importing users and lists the accepted values in the error. email_verified has to be a date or an epoch timestamp. Omit it, or set it to 0, true, or a value that isn't a date, and the address is imported as an unverified email. Include created_at to keep each user's original signup date. An id field works in place of userId.

The SQL below mirrors the query clerk migrate export authjs runs against Prisma's User table on Postgres, so both paths produce the same user fields. The export also reads the account table to find each user's OAuth providers and to apply --trust-oauth-emails, which this query skips. Substitute your own table name if your adapter didn't create User, such as next_auth.users for the Supabase adapter, and swap the double quotes for backticks on MySQL. On a legacy NextAuth table, select email_verified and created_at as they are.

SELECT id, name, email, "emailVerified" AS email_verified FROM "User"

Verify the migration

  1. Read what the run did. It lists the users that failed or were skipped, and why:

    terminal
    clerk migrate runs <import_run_id>
  2. In the Clerk Dashboard, navigate to the Users page and check that your users are listed. Run clerk users list to check from your terminal.

  3. Sign in to your Clerk-secured application with one of the migrated accounts.

Undo the migration

Preview the users the import created, using the import run's ID:

terminal
clerk migrate undo <import_run_id> --dry-run

Then delete them:

terminal
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.

Finding further support for migrating from Auth.js to Clerk

If your Auth.js integration needs something this guide doesn't cover, contact support or ask in the Discord community.

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

What did you think of this content?

Last updated on