NextAuth to Auth.js Migration Guide: Fixing Every Breaking Change

NextAuth to Auth.js Migration Guide: Fixing Every Breaking Change

By Elena Rodriguez, Developer Experience Editorial Desk · April 27, 2026 · 9 min read

Quick Answer

Auth.js v5 (the rebrand of NextAuth) replaces `next-auth` with `@auth/core` plus framework adapters, swaps `getServerSession()` for a universal `auth()` helper, moves config into a root `auth.ts`, rewrites the middleware contract, and bumps every database adapter to a new namespace. Expect roughly a half-day of mechanical edits per app, plus testing.

A Migration That Looks Easier Than It Is

NextAuth has been the default authentication library for Next.js since 2020. In late 2024 it rebranded to Auth.js and shipped v5 — a rewrite that fixes most of the rough edges that App Router users complained about, but at the cost of a non-trivial migration. By 2026 most production apps have either migrated or built up enough technical debt that the migration is now urgent.

This guide walks through every breaking change between NextAuth v4 and Auth.js v5, with before/after code, the errors you will hit, and the fixes that actually work. It assumes you are running Next.js 14 or 15 with the App Router. Pages Router migrations are similar but the middleware and Server Component bits do not apply.

A Quick History

NextAuth started as a Pages Router-first library. The original API — [...nextauth].js route, getServerSession(), useSession() — was designed for getInitialProps and getServerSideProps. When the App Router landed in Next.js 13, NextAuth bolted on App Router support but the seams showed: getServerSession() worked but felt foreign, middleware needed the awkward withAuth wrapper, and Edge runtime support was a long-running open issue.

Auth.js v5 (the v5 release of next-auth, branded as Auth.js) is the App Router-first rewrite. The same maintainers, mostly the same providers, but a config API designed for Server Components, Server Actions, Route Handlers, and Edge middleware as first-class citizens. The Auth.js team also published bindings for SvelteKit, SolidStart, Express, and Qwik — the rebrand reflects that the core is now framework-agnostic.

If you want the broader Next.js context before diving in, our Next.js authentication tutorial covers the App Router patterns that v5 was designed around.

Why Should You Migrate to Auth.js v5?

Three concrete reasons:

  1. The `auth()` helper is one function for every context. In v4 you used getServerSession() in API routes, getServerSession() (different overload) in Server Components, useSession() on the client, and a separate getToken() in middleware. In v5, auth() works in all four places.
  2. Edge runtime support actually works. v4 required workarounds (splitting config, avoiding adapter imports). v5 made the split first-class.
  3. Modular providers and adapters. v5 published every provider and adapter as a separate package, which keeps your bundle smaller and lets the Auth.js team ship provider fixes without bumping the core.

The downside is the migration cost. Plan for half a day of mechanical edits per app, plus a day of testing. Plan for two days if you have custom database adapter logic or non-trivial JWT/session callbacks.

Step 1: Install the New Packages

The package on npm is still called next-auth, but the version is v5+. The adapter packages all moved namespace from @next-auth/* to @auth/*.

bash
# Remove old packages
npm uninstall next-auth @next-auth/prisma-adapter

# Install v5 + new adapter namespace
npm install next-auth@beta @auth/prisma-adapter

At the time of writing the v5 release is still tagged @beta for some adapter combos. The Auth.js install docs show the current stable tag. Match what they recommend.

Step 2: Rewrite the Config Into a Root auth.ts

In v4 your config lived in app/api/auth/[...nextauth]/route.ts. In v5 it moves to a root auth.ts (or src/auth.ts) and the API route becomes a thin re-export.

v4 — single file:

ts
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { prisma } from '@/lib/prisma';

const handler = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
  ],
  callbacks: {
    async session({ session, token }) {
      if (session.user) session.user.id = token.sub!;
      return session;
    },
  },
});

export { handler as GET, handler as POST };

v5 — split into two files:

ts
// auth.config.ts (Edge-safe, used by middleware)
import type { NextAuthConfig } from 'next-auth';
import Google from 'next-auth/providers/google';

export default {
  providers: [
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user;
      const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
      if (isOnDashboard) return isLoggedIn;
      return true;
    },
  },
} satisfies NextAuthConfig;
ts
// auth.ts (Node, full config with adapter)
import NextAuth from 'next-auth';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from '@/lib/prisma';
import authConfig from './auth.config';

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  session: { strategy: 'jwt' },
  callbacks: {
    async session({ session, token }) {
      if (session.user) session.user.id = token.sub!;
      return session;
    },
  },
  ...authConfig,
});
ts
// app/api/auth/[...nextauth]/route.ts (thin re-export)
export { GET, POST } from '@/auth';

The split lets middleware import auth.config.ts (which has no Node-only dependencies and runs on the Edge) while Server Components and Route Handlers import the full auth.ts with the database adapter.

Step 3: Replace getServerSession With auth()

Every server-side session read changes. getServerSession() is gone. The new pattern is to import auth from your root config and call it.

v4:

ts
// In a Server Component
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';

export default async function Page() {
  const session = await getServerSession(authOptions);
  if (!session) redirect('/signin');
  return <Dashboard user={session.user} />;
}

v5:

ts
import { auth } from '@/auth';

export default async function Page() {
  const session = await auth();
  if (!session) redirect('/signin');
  return <Dashboard user={session.user} />;
}

The same auth() call works in Route Handlers, Server Actions, and middleware. This is the single biggest ergonomic improvement in v5.

Step 4: Migrate the Middleware

withAuth is gone. Middleware now wraps with the auth export.

v4:

ts
// middleware.ts
export { default } from 'next-auth/middleware';

export const config = {
  matcher: ['/dashboard/:path*'],
};

v5:

ts
// middleware.ts
import NextAuth from 'next-auth';
import authConfig from './auth.config';

export const { auth: middleware } = NextAuth(authConfig);

export const config = {
  matcher: ['/dashboard/:path*'],
};

If you need custom logic in middleware (rate limiting, geo blocking), wrap the auth helper:

ts
import NextAuth from 'next-auth';
import authConfig from './auth.config';

const { auth } = NextAuth(authConfig);

export default auth((req) => {
  if (!req.auth && req.nextUrl.pathname !== '/signin') {
    const newUrl = new URL('/signin', req.nextUrl.origin);
    return Response.redirect(newUrl);
  }
});

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

The redirect-loop trap mentioned in the FAQs lives here. If your matcher catches /signin and your middleware always redirects unauthenticated requests to /signin, you loop. Always exclude the auth pages from the matcher or check the path explicitly.

Step 5: Client Hooks Mostly Stay

The useSession() hook still works but the import path matters.

v4 and v5 — same code:

tsx
'use client';
import { useSession } from 'next-auth/react';

export function UserAvatar() {
  const { data: session, status } = useSession();
  if (status === 'loading') return <Skeleton />;
  if (!session?.user) return null;
  return <Avatar src={session.user.image!} />;
}

SessionProvider is also unchanged in import location. The breaking change for client code is that you no longer need to wrap your entire app in SessionProvider — Server Components can read the session directly with auth(). Many apps remove the provider entirely after migration and only add it back where they need reactive client-side updates.

Step 6: Database Adapter Swaps

Every adapter package moved. Here is the lookup table:

  • @next-auth/prisma-adapter → @auth/prisma-adapter
  • @next-auth/drizzle-adapter → @auth/drizzle-adapter
  • @next-auth/mongodb-adapter → @auth/mongodb-adapter
  • @next-auth/supabase-adapter → @auth/supabase-adapter

The Drizzle adapter has the largest schema delta. v5 added support for credentials accounts and tightened the foreign key constraints. The Auth.js docs publish a reference Drizzle schema — diff yours against it before migrating. For broader deployment guidance see our Vercel and Supabase deployment gotchas guide.

For Prisma, the schema additions are minor:

prisma
model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?
  refresh_token_expires_in Int? // <- new in some providers

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

Run prisma migrate dev --name authjs-v5 after editing.

Step 7: Provider Config Breaking Changes

Most providers are stable, but defaults have tightened. The two most common gotchas:

Google: Default scopes used to include profile email openid. v5 requires you to declare them:

ts
Google({
  clientId: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  authorization: {
    params: {
      scope: 'openid email profile',
      prompt: 'consent',
      access_type: 'offline',
      response_type: 'code',
    },
  },
}),

GitHub: user:email is no longer included by default. If your callbacks read profile.email, declare it:

ts
GitHub({
  clientId: process.env.GITHUB_CLIENT_ID,
  clientSecret: process.env.GITHUB_CLIENT_SECRET,
  authorization: { params: { scope: 'read:user user:email' } },
}),

For broader TypeScript hygiene around provider configs, see our TypeScript best practices guide.

Step 8: Environment Variables

NEXTAUTH_SECRET is now AUTH_SECRET. NEXTAUTH_URL is now AUTH_URL (and is auto-detected on Vercel — you can usually drop it). The old names still work but emit deprecation warnings.

bash
# .env.local
AUTH_SECRET=<openssl rand -base64 32>
AUTH_GOOGLE_ID=<from Google Cloud Console>
AUTH_GOOGLE_SECRET=<from Google Cloud Console>

The provider environment variable convention also changed. v5 will auto-detect AUTH_<PROVIDER>_ID and AUTH_<PROVIDER>_SECRET if you do not pass them explicitly. This shrinks your config:

ts
// With AUTH_GOOGLE_ID and AUTH_GOOGLE_SECRET in env, this is enough:
Google,

The full list of detected variables is in the Auth.js environment docs.

Step 9: Testing Strategy

You cannot guarantee a clean migration without testing. Here is the order:

  1. Unit-test the JWT and session callbacks. Mock the inputs, assert the outputs, run before and after migration. The shape of token and session should be identical.
  2. Run an E2E flow with Playwright. Sign in with a test account, navigate to a protected page, sign out. Capture the cookies and compare across versions.
  3. Test middleware with both authed and unauthed requests. Use curl -i to verify the redirect status codes and Set-Cookie headers.
  4. Test the OAuth callback URL specifically. A misconfigured trustHost setting (now trustHost: true by default behind a proxy) is the #1 cause of "works locally, fails in prod" issues.

Common Errors and Fixes

`MissingSecret: Please define a 'secret' in production` — Set AUTH_SECRET in your environment. The NEXTAUTH_SECRET fallback works but emits warnings.

`UntrustedHost` — Behind a load balancer, set AUTH_TRUST_HOST=true in env, or pass trustHost: true in your config.

`TypeError: Cannot read properties of undefined (reading 'user')` — You called auth() without awaiting it, or you imported auth from the wrong file (typically the config file instead of the helper file).

`OAuthCallbackError: invalid_grant` — The OAuth flow completed but the token exchange failed. Almost always a clock-skew issue or a stale cached refresh token. Sign out, clear the relevant rows in the Account table, and retry.

Redirect loop on `/signin` — Your matcher includes the signin page. Add an explicit exclusion or check the path inside your wrapped middleware.

Final Checklist

Before flipping production traffic to v5:

  • [ ] All getServerSession() calls replaced with auth()
  • [ ] auth.config.ts has no Node-only imports (no Prisma, no fs, no crypto beyond Web Crypto)
  • [ ] Middleware tested with authed and unauthed requests
  • [ ] OAuth providers tested end-to-end (sign in, sign out, refresh token flow)
  • [ ] Database adapter package swapped and schema migrated
  • [ ] AUTH_SECRET set in production
  • [ ] Cookie name verified to be unchanged (or session-aware migration in place)
  • [ ] Sentry / observability still capturing auth errors

When all of those are checked, ship it. The migration looks intimidating because it touches every layer, but the actual line count of changes is small and the result is dramatically easier to maintain.


For the wider context on shipping authentication in modern Next.js apps, see our pillar guide: [Next.js Authentication Tutorial 2026](/blog/nextjs-authentication-tutorial-2026).

Sources

The primary sources this article cites:

Key Takeaways

  • Auth.js v5 is the App Router-first rewrite of NextAuth; the npm package is still `next-auth`, but config, helpers and adapters changed.
  • One `auth()` helper replaces `getServerSession()` and works in Server Components, Route Handlers, Server Actions and middleware.
  • Split config into an Edge-safe `auth.config.ts` for middleware and a full `auth.ts` that adds the database adapter.
  • Adapter packages moved from `@next-auth/*` to `@auth/*`, and the Drizzle adapter has the largest schema changes.
  • `NEXTAUTH_SECRET` and `NEXTAUTH_URL` become `AUTH_SECRET` and `AUTH_URL`; the old names still work but emit deprecation warnings.
  • Plan about half a day of edits per app plus a day of testing, or two days with custom adapter logic.

Frequently Asked Questions

Do I have to migrate? Can I stay on v4?

You can stay on v4, but it is effectively end-of-life. Known CVEs will still get security patches, while new providers, App Router improvements and Edge runtime fixes are v5 only. On Next.js 14+ with the App Router, v4's missing `auth()` helper, awkward Server Component access and Edge incompatibility add friction quickly, so plan a migration window in 2026.

Will my existing user sessions survive the migration?

Usually, yes. With the default JWT strategy and the same `AUTH_SECRET`, the cookie format is compatible, and database-strategy sessions survive because the row schema is unchanged. The main catch is that the cookie name can change from `next-auth.session-token` to `authjs.session-token`, so set `cookies.sessionToken.name` explicitly during migration to avoid logging users out.

What breaks with the Prisma adapter?

Swap `@next-auth/prisma-adapter` for `@auth/prisma-adapter`. The schema is mostly compatible, but some providers now need `refresh_token_expires_in` on the Account model as `Int?`, and the `VerificationToken` model uses a composite key that older migrations may lack. Diff your schema against the latest Auth.js Prisma schema, then run `prisma migrate dev`.

My middleware redirects loop after migration. What is wrong?

Your middleware matcher probably includes the sign-in page. If middleware sends every unauthenticated request to `/signin` and the matcher also catches `/signin`, requests loop forever. Exclude the auth pages from the matcher, or check the path inside the wrapped middleware, for example `if (req.nextUrl.pathname === '/signin') return`, before redirecting.

How do I test the migration without breaking production?

Run v4 and v5 side by side behind a feature flag. Deploy the v5 code to a preview URL, sign in with a test account, and check the cookie, the `/api/auth/session` payload and protected routes. Unit-test your JWT and session callbacks too. Then roll out gradually: 1% of traffic, then 10%, then everyone.

About the Author

Elena Rodriguez avatar

Elena Rodriguez

Developer Experience Editorial Desk

Developer Experience Editorial Desk · Web3AIBlog

Elena Rodriguez is a pen name for our developer-experience editorial desk. Posts under this byline are written and reviewed by working engineers covering full-stack development, Web3 dApp architecture, deployment workflows, build tooling, and developer productivity. The desk specializes in turning real production debugging — failed deploys, flaky tests, memory leaks, broken migrations — into reproducible field manuals. Code samples in our tutorials are built from and verified against the official SDKs and documentation, with library versions pinned, before publication.