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
Your existing user schema is likely compatible with Better Auth, so no changes are needed.
Session Schema
Map the following fields in the session schema:
expires
→expiresAt
sessionToken
→token
Accounts Schema
Map these fields in the accounts schema:
providerAccountId
→accountId
refresh_token
→refreshToken
access_token
→accessToken
access_token_expires
→accessTokenExpiresAt
id_token
→idToken
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:
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:
Server-Side Session Handling
Use the auth
instance to get session data on the server:
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.