Migrating from Auth.js to Better Auth: A Step-by-Step Guide

npmixnpmix
102
Authjs and Nextjs

Thinking about switching authentication providers in your Next.js app? Better Auth offers more flexibility, cleaner APIs, and faster performance. Here's a complete step-by-step guide to migrating from Auth.js to Better Auth—without losing data or breaking your app.

🔄 TL;DR

  • ✅ Fully migrate from Auth.js to Better Auth without database schema changes
  • 🔄 Map user, session, and account schemas with field mapping (no need to rename columns)
  • 🔐 Update route handlers and session logic for Next.js App Router
  • 📦 Replace useSession and signIn with Better Auth's type-safe alternatives
  • 💡 Keep all existing user sessions active during and after migration

🧭 Why Migrate to Better Auth?

Before diving into the migration steps, here's why many teams are making the switch:

  • Type-safe APIs with full TypeScript support and better developer experience
  • Granular control over authentication flow, session handling, and database schema
  • Significantly improved performance in large-scale applications
  • Built-in support for modern auth flows including passwordless, multi-provider login, and MFA
  • Simplified OAuth integration with major providers like Google, GitHub, and Discord

📁 Step 1: Install Better Auth

If you haven't already, install Better Auth in your project:

bash
1npm install better-auth
2# or
3yarn add better-auth
4# or
5pnpm add better-auth

Then set up the core configuration in your auth.ts file:

typescript
1// server/auth.ts
2import { betterAuth } from "better-auth";
3import { prismaAdapter } from "better-auth/adapters/prisma";
4import { PrismaClient } from "@prisma/client";
5import { nextCookies } from "better-auth/nextjs";
6
7const prisma = new PrismaClient();
8
9export const auth = betterAuth({
10  secret: process.env.BETTER_AUTH_SECRET,
11  emailAndPassword: {
12    enabled: true,
13  },
14  database: prismaAdapter(prisma, {
15    provider: "postgresql",
16  }),
17  plugins: [nextCookies()],
18});

Make sure to set the BETTER_AUTH_SECRET environment variable in your .env file. This should be a strong, random string (at least 32 characters).

🧱 Step 2: Map Your Database Schema

One of the biggest advantages of Better Auth is that you don't need to rename your database fields. Instead, you can map your existing Auth.js schema to Better Auth's expected structure.

👤 User Schema Mapping

Auth.js FieldBetter Auth FieldNotes
emailVerified (v4)emailVerifiedchange datetime → boolean

📑 Session Schema Mapping

Auth.js FieldBetter Auth FieldNotes
expiresexpiresAt
sessionTokentoken
(Add)createdAt, updatedAtfields (datetime)

In your auth.ts configuration:

typescript
1export const auth = betterAuth({
2  // Other configs
3  session: {
4    fields: {
5      expiresAt: "expires",
6      token: "sessionToken",
7    },
8  },
9});

🧾 Account Schema Mapping

Auth.js FieldBetter Auth FieldNotes
provider (v4)providerId
providerAccountIdaccountId
refresh_tokenrefreshToken
access_tokenaccessToken
access_token_expiresaccessTokenExpiresAt
expires_at (v4)accessTokenExpiresAt
id_tokenidToken
(Remove)session_state, type, token_typeNot required by Better Auth
(Add)createdAt, updatedAtfields (datetime)

In your auth.ts configuration:

typescript
1export const auth = betterAuth({
2  // Other configs
3  account: {
4    fields: {
5      providerId: "provider", // For Auth.js v4
6      accountId: "providerAccountId",
7      refreshToken: "refresh_token",
8      accessToken: "access_token",
9      accessTokenExpiresAt: "expires_at", // For Auth.js v4
10      idToken: "id_token",
11    },
12  },
13});

📐 Step 3: Update Your Prisma Schema

If you're using Prisma, you can keep your existing schema and use the @map() directive to map the fields:

prisma
1model Session {
2  id        String   @id @default(cuid())
3  expiresAt DateTime @map("expires")
4  token     String   @unique @map("sessionToken")
5  userId    String
6  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
7  createdAt DateTime @default(now())
8  updatedAt DateTime @updatedAt
9
10  @@index([userId])
11}
12
13model Account {
14  id                String   @id @default(cuid())
15  userId            String
16  providerId        String   @map("provider")
17  accountId         String   @map("providerAccountId")
18  refreshToken      String?  @map("refresh_token")
19  accessToken       String?  @map("access_token")
20  accessTokenExpiresAt DateTime? @map("expires_at")
21  idToken           String?  @map("id_token")
22  createdAt         DateTime @default(now())
23  updatedAt         DateTime @updatedAt
24  user              User     @relation(fields: [userId], references: [id], onDelete: Cascade)
25
26  @@unique([providerId, accountId])
27  @@index([userId])
28}
29
30model User {
31  id            String    @id @default(cuid())
32  name          String?
33  email         String?   @unique
34  emailVerified Boolean?  @default(false)
35  image         String?
36  accounts      Account[]
37  sessions      Session[]
38  createdAt     DateTime  @default(now())
39  updatedAt     DateTime  @updatedAt
40}

After updating your schema, run a migration:

bash
1npx prisma migrate dev --name better-auth-migration

🔁 Step 4: Update Your Route Handler

In your app/api/auth directory, rename the [...nextauth] folder to [...all] to avoid confusion. Then, update the route.ts file:

typescript
1// app/api/auth/[...all]/route.ts
2import { toNextJsHandler } from "better-auth/next-js";
3import { auth } from "~/server/auth";
4
5export const { POST, GET } = toNextJsHandler(auth);

This handler will process all authentication-related requests, including sign-in, sign-out, and session management.

🧠 Step 5: Refactor the Client

Create a reusable auth client file to centralize your authentication hooks and functions:

typescript
1// lib/auth-client.ts
2import { createAuthClient } from "better-auth/react";
3
4export const authClient = createAuthClient({
5  baseURL: process.env.NEXT_PUBLIC_BASE_URL, // Optional if your API is on the same domain
6});

Example: Social Login with Discord

Update your social login functions to use Better Auth's type-safe API:

typescript
1import { authClient } from "@/lib/auth-client";
2
3export const signInGoogle = async () => {
4  const { data, error } = authClient.signIn.social({
5    provider: "google",
6    callbackUrl: "/dashboard", // Optional redirect after successful login
7  });
8
9  if (error) {
10    console.error("Failed to sign in:", error.message);
11    return null;
12  }
13
14  // Success! User is now logged in
15  return data;
16};

Example: Email and Password Login for server component

To enable email and password authentication, you need to set the emailAndPassword.enabled option to true in the auth configuration.

typescript
1// @/lib/auth.ts
2import { betterAuth } from "better-auth";
3 
4export const auth = betterAuth({
5  emailAndPassword: { 
6    enabled: true, 
7  }, 
8});
typescript
1"use server";
2
3import { auth } from "@/lib/auth";
4import { headers } from "next/headers";
5
6export const signInWithEmail = async (email: string, password: string) => {
7  try {
8    await auth.api.signInEmail({
9      body: {
10        email,
11        password,
12      },
13    });
14
15    return {
16      success: true,
17      message: "Signed in successfully.",
18    };
19  } catch (error) {
20    const e = error as Error;
21
22    return {
23      success: false,
24      message: e.message || "An unknown error occurred.",
25    };
26  }
27};

Example: Email and Password Login for client component

typescript
1import { authClient } from "@/lib/auth-client";
2
3export const signInWithEmail = async (email: string, password: string) => {
4  const { data, error } = authClient.signIn.email({
5    email,
6    password,
7    callbackUrl: "/dashboard", // Optional redirect after successful login
8  });
9
10  if (error) {
11    return { success: false, message: error.message };
12  }
13
14  return { success: true, data };
15};

Example: Replace useSession

Replace Auth.js's useSession hook with Better Auth's version:

typescript
1"use client"
2
3import { createAuthClient } from "better-auth/react"
4const { useSession } = createAuthClient() 
5
6export const Profile = () => {
7  const { data: session, isPending, error } = useSession();
8
9  if (isPending) return <div>Loading user information...</div>;
10  if (error) return <div>Error: {error.message}</div>;
11  if (!session) return <div>Please sign in to view your profile</div>;
12
13  return (
14    <div>
15      <h1>Welcome, {session.user.name || 'User'}</h1>
16      <img src={session.user.image || '/default-avatar.png'} alt="Profile" />
17      <pre>{JSON.stringify(session, null, 2)}</pre>
18    </div>
19  );
20};

🧾 Step 6: Server Actions and Middleware

Server-Side Session Access

For server components or server actions, use the auth instance to get session data:

typescript
1// Server Component
2// app/dashboard/page.tsx
3
4import { auth } from "@/lib/auth";
5import { headers } from "next/headers";
6
7export default async function Dashboard() {
8  const session = await auth.api.getSession({
9    headers: headers(),
10  });
11
12  if (!session) {
13    redirect("/login");
14  }
15
16  return (
17    <div>
18      <h1>Welcome, {session.user.name}</h1>
19      {/* Dashboard content */}
20    </div>
21  );
22}
typescript
1// Server Action
2"use server";
3
4import { auth } from "~/server/auth";
5import { headers } from "next/headers";
6import { revalidatePath } from "next/cache";
7
8export const updateUserProfile = async (formData: FormData) => {
9  const session = await auth.api.getSession({
10    headers: headers(),
11  });
12
13  if (!session) {
14    throw new Error("Unauthorized");
15  }
16
17  const updateProfile = await prisma.user.update({
18    where: {
19      id: session.user.id,
20    },
21    data: {
22      name: formData.get("name") as string,
23      email: formData.get("email") as string,
24    },
25  });
26
27  revalidatePath("/profile");
28  return { success: true };
29};
typescript
1// app/profile/page.tsx
2
3import {updateUserProfile} from "@/server/actions";
4
5export default function Profile() {
6  return (
7    <div>
8      <h1>Profile</h1>
9      <form action={updateUserProfile}>
10        <input type="text" name="name" />
11        <input type="email" name="email" />
12        <button type="submit">Update Profile</button>
13      </form>
14    </div>
15  );
16}

Middleware (Optional)

To protect routes with middleware, create a middleware.ts file in your project root:

typescript
1// middleware.ts
2import { NextRequest, NextResponse } from "next/server";
3import { getSessionCookie } from "better-auth/cookies";
4
5export async function middleware(request: NextRequest) {
6  const sessionCookie = getSessionCookie(request);
7
8  // Redirect unauthenticated users to login page
9  if (!sessionCookie && !request.nextUrl.pathname.startsWith("/login")) {
10    const loginUrl = new URL("/login", request.url);
11    loginUrl.searchParams.set("callbackUrl", request.nextUrl.pathname);
12    return NextResponse.redirect(loginUrl);
13  }
14
15  // Optional: Role-based access control
16  if (
17    sessionCookie &&
18    request.nextUrl.pathname.startsWith("/admin") &&
19    sessionCookie.user.role !== "admin"
20  ) {
21    return NextResponse.redirect(new URL("/dashboard", request.url));
22  }
23
24  return NextResponse.next();
25}
26
27export const config = {
28  matcher: ["/dashboard/:path*", "/profile/:path*", "/admin/:path*"],
29};

✅ Final Checklist

TaskStatusNotes
Install Better Authnpm install better-auth
Update auth configurationMap fields to preserve existing data
Update Prisma schemaUse @map() directives
Update route handlerRename [...nextauth] to [...all]
Create auth clientExport hooks and functions
Update client componentsReplace useSession and signIn calls
Update server componentsUse auth.api.getSession
Configure middlewareProtect routes as needed

🎉 Wrapping Up

You've successfully migrated from Auth.js to Better Auth! Your application now benefits from:

  • Type-safe authentication APIs
  • Improved performance and security
  • More flexible session management
  • Better developer experience

All of this without losing any user data or breaking existing sessions.

Want to explore more? Check out the Better Auth docs or clone the demo repository for complete examples.

🙋‍♂️ FAQ

Q: Does this migration break existing user sessions?
A: No—if you map your fields properly, existing users will remain logged in throughout and after the migration.

Q: Can I use this with server actions and server components?
A: Yes. Better Auth works seamlessly with Next.js 14/15 features including server components, server actions, and middleware.

Q: What about OAuth providers like Google/GitHub/Discord?
A: They're fully supported via the .social() method. Better Auth simplifies OAuth integration with improved error handling.

Q: Do I need to change my database schema?
A: No. You can map existing fields without renaming them, allowing for a smooth migration without data loss.

Q: How do I handle custom fields in my user model?
A: Better Auth supports custom fields through the user.fields configuration option, giving you full control over your data model.

Similar articles

Never miss an update

Subscribe to receive news and special offers.

By subscribing you agree to our Privacy Policy.