# Migrate from NextAuth.js (Auth.js)

> Move a NextAuth.js or Auth.js app's users, OAuth accounts and Credentials password hashes into Pontive by writing the pontive-users/v1 file from the adapter's tables, then replace NextAuth with pontkit.

Source: https://www.pontive.com/docs/guides/migrate/nextauth

`pontive migrate` has no NextAuth exporter: NextAuth keeps its users in your own database, through its
adapter, so you write the import file with one query and import it with the CLI. Read
[Migrate to Pontive](/docs/guides/migrate) first for how runs, dry runs and matching work.

## 1. What moves and what does not [#1-what-moves-and-what-does-not]

| Moves | Does not move |
| --- | --- |
| The adapter's users: `id`, `name`, `email`, `emailVerified`, `image` | Sessions in the `sessions` table: users sign in once more |
| Google, GitHub and Apple accounts from the `accounts` table, by `providerAccountId` | Accounts of providers Pontive has no portable type for (Discord, Twitter, …): those users link by verified email, once you set that provider up in Pontive |
| Password hashes, if your Credentials provider stores them in a column you added | Users without an email; verification tokens |
| The NextAuth user id, as legacy subject and `external_id` | |

Auth.js sets `emailVerified` only for the email provider, so OAuth-only users come out unverified.
That is fine: their imported identity signs them in without an email match, and Pontive verifies an
unverified address at the first sign-in.

## 2. Create the migration source [#2-create-the-migration-source]

```sh
export PONTIVE_SECRET_KEY=pontive_sk_test_us_...   # an admin key of your development instance

npx pontive@latest migrate source create --name "NextAuth" --type nextauth   # prints msrc_...
```

## 3. Write the file, then dry run [#3-write-the-file-then-dry-run]

This query reads the tables of the Postgres adapter (`@auth/pg-adapter`: `users`, `accounts`) and
writes one `user` line of `pontive-users/v1` per user:

```sql title="nextauth-export.sql"
select jsonb_strip_nulls(jsonb_build_object(
  'kind', 'user',
  'legacy_subject', u.id::text,
  'external_id', u.id::text,
  'email', u.email,
  'email_verified', u."emailVerified" is not null,
  'name', u.name,
  'picture', u.image,
  'external_identities', (
    select jsonb_agg(jsonb_build_object(
      'connection_type', a.provider,
      'provider_user_id', a."providerAccountId"))
    from accounts a
    where a."userId" = u.id and a.provider in ('google', 'github', 'apple')
  )
))
from users u
where u.email is not null
order by u.id;
```

- **Prisma adapter:** the tables are `"User"` and `"Account"` (quoted), unless your schema maps them.
- **Drizzle adapter:** `"user"` and `"account"`.
- The column names (`"emailVerified"`, `"userId"`, `"providerAccountId"`) are the same in all three.
- An OIDC provider you configured yourself (id `my-idp`, say) can come over as `oidc` when Pontive's
  connection uses the same issuer: write `case a.provider when 'my-idp' then 'oidc' else a.provider end`
  as the `connection_type`, and add `'my-idp'` to the list.

**Credentials provider.** If your app stores a password hash, say in `users.password`, add it after
`'picture'`. Check which library wrote it; never guess:

```sql
  'password_hash', case
    when u.password like '$2_$%' then jsonb_build_object('hasher', 'bcrypt', 'value', u.password)
    when u.password like '$argon2%' then jsonb_build_object('hasher', 'argon2', 'value', u.password)
  end,
```

bcrypt and bcryptjs write `$2a$` or `$2b$`, argon2 writes `$argon2id$`. Other formats, such as
scrypt or PBKDF2, have their own `hasher`; see [the file format](/docs/guides/migrate#any-other-system-the-file-format).

Run it with `psql`, keeping the file private since it holds hashes, then dry-run:

```sh
(umask 077; psql "$DATABASE_URL" -XAt -f nextauth-export.sql > pontive-users.ndjson)

npx pontive@latest migrate import pontive-users.ndjson --source msrc_...
```

## 4. Map roles and connections [#4-map-roles-and-connections]

NextAuth has no organizations or roles. Map each provider to the Pontive app's auth connection:

```sh
npx pontive@latest migrate import pontive-users.ndjson --source msrc_... \
  --identity-connection google=app_...:google \
  --identity-connection github=app_...:github
```

A type you leave out is dropped from the rows and counted, and those users link by verified email.

## 5. Apply [#5-apply]

```sh
npx pontive@latest migrate import pontive-users.ndjson --source msrc_... \
  --identity-connection google=app_...:google \
  --identity-connection github=app_...:github \
  --apply --delete-after
```

Failed rows: `npx pontive@latest migrate records uimp_... --outcome failed`.

## 6. Swap the SDK [#6-swap-the-sdk]

`@pontive/pontkit-nextjs` in [server-session](/docs/sdk/server-sessions) mode works the way NextAuth
does: the server signs in with a client secret and keeps an encrypted session cookie, under
`/api/auth`. Create a confidential app in Pontive with the redirect URI
`https://<your origin>/api/auth/callback`, then:

```sh
npm uninstall next-auth @auth/prisma-adapter   # or your adapter
npm install @pontive/pontkit-nextjs
```

```ts title="lib/pontive.ts"
import { pontiveAuth } from "@pontive/pontkit-nextjs/server";

// Replaces: export const { handlers, auth, signIn, signOut } = NextAuth({ ... });
export const pontive = pontiveAuth({
  issuer: process.env.PONTIVE_ISSUER!, // https://<auth domain>
  clientId: process.env.PONTIVE_CLIENT_ID!,
  clientSecret: process.env.PONTIVE_CLIENT_SECRET!,
  sessionSecret: process.env.PONTIVE_SESSION_SECRET!, // 32+ random characters
  baseUrl: process.env.PUBLIC_URL, // https://app.acme.com
});
```

```ts title="app/api/auth/[...pontive]/route.ts"
import { pontive } from "@/lib/pontive";

export const { GET, POST } = pontive.handlers;
```

| NextAuth | pontkit |
| --- | --- |
| `app/api/auth/[...nextauth]/route.ts` | `app/api/auth/[...pontive]/route.ts` |
| `export { auth as middleware }` | `export function proxy(req) { return pontive.middleware(req); }` |
| `await auth()`, `session.user.id` | `await pontive.auth()`, `session.user.id` (`usr_…`) |
| `signIn()` | a link to `/api/auth/login` |
| `signOut()` | a link to `/api/auth/logout`, which also ends the Pontive session |
| `session.accessToken` from your `jwt` callback | `session.accessToken`, refreshed for you |
| The Credentials provider's `authorize()` | nothing: Pontive checks the imported hash |

Delete the `jwt` and `session` callbacks that refreshed tokens: pontkit refreshes and handles
rotation itself. Code that reads the old user id reads it from the token once the claims template
carries it (step 7).

**Not ready to replace NextAuth?** Add Pontive as an OIDC provider to NextAuth instead
([Using Pontive with NextAuth.js](/docs/sdk/nextauth)). With a database adapter, NextAuth then
creates a new user for each first Pontive sign-in, so plan how those rows meet the old ones.

## 7. Cut over [#7-cut-over]

Follow the [cutover checklist](/docs/guides/migrate#cut-over). For NextAuth in particular:

- Run the query again just before switching and import that file into the same run with
  `--run uimp_...`.
- If your tables key users by the NextAuth id, set the app's claims template to
  `{ "legacy_user_id": "{{ user.external_id }}" }`, or move those columns to Pontive's `sub`.
- Remove the old OAuth apps' NextAuth callback URLs once nothing uses them.

## 8. Revert [#8-revert]

```sh
npx pontive@latest migrate revert uimp_...          # dry run
npx pontive@latest migrate revert uimp_... --apply
```

Users who have signed in to Pontive since are kept and listed. Your database is untouched. See
[Revert](/docs/guides/migrate#revert).
