Migrating from NextAuth.js to Better Auth
In this guide, we’ll walk through the steps to migrate a project from NextAuth.js to Better Auth, ensuring no loss of data or functionality. While this guide focuses on Next.js, it can be adapted for other frameworks as well.
Before You Begin
Before starting the migration process, set up Better Auth in your project. Follow the installation guide to get started.
Mapping Existing Columns
Instead of altering your existing database column names, you can map them to match Better Auth's expected structure. This allows you to retain your current database schema.
User Schema
Map the following fields in the user schema:
- (next-auth v4)
emailVerified: datetime → boolean
Session Schema
Map the following fields in the session schema:
expires→expiresAtsessionToken→token- (next-auth v4) add
createdAtwith datetime type - (next-auth v4) add
updatedAtwith datetime type
Make sure to have createdAt and updatedAt fields on your session schema.
Account Schema
Map these fields in the account schema:
- (next-auth v4)
provider→providerId providerAccountId→accountIdrefresh_token→refreshTokenaccess_token→accessToken- (next-auth v3)
access_token_expires→accessTokenExpiresAtand int → datetime - (next-auth v4)
expires_at→accessTokenExpiresAtand int → datetime id_token→idToken- (next-auth v4) add
createdAtwith datetime type - (next-auth v4) add
updatedAtwith datetime type
Remove the session_state, type, and token_type fields, as they are not required by Better Auth.
Note: If you use ORM adapters, you can map these fields in your schema file.
Example with Prisma:
Make sure to have createdAt and updatedAt fields on your account schema.
Update the Route Handler
In the app/api/auth folder, rename the [...nextauth] file to [...all] to avoid confusion. Then, update the route.ts file as follows:
Update the Client
Create a file named auth-client.ts in the lib folder. Add the following code:
Social Login Functions
Update your social login functions to use Better Auth. For example, for Discord:
Update useSession Calls
Replace useSession calls with Better Auth’s version. Example:
Middleware
To protect routes with middleware, refer to the Next.js middleware guide.
Wrapping Up
Congratulations! You’ve successfully migrated from NextAuth.js to Better Auth. For a complete implementation with multiple authentication methods, check out the demo repository.
Better Auth offers greater flexibility and more features—be sure to explore the documentation to unlock its full potential.