Skip to content

feat: migrate from NextAuth to Better-Auth#6

Merged
indulgeback merged 8 commits into
mainfrom
feat/migrate-to-better-auth
Jan 21, 2026
Merged

feat: migrate from NextAuth to Better-Auth#6
indulgeback merged 8 commits into
mainfrom
feat/migrate-to-better-auth

Conversation

@indulgeback

Copy link
Copy Markdown
Owner

🎯 概述

完成从 NextAuth v4 到 Better-Auth 的完整迁移,使用 Prisma + PostgreSQL 进行数据库持久化认证。


✨ 主要变更

🔑 认证库替换

  • 移除: next-auth, @auth/core
  • 新增: better-auth (v1.4.16), @prisma/adapter-pg (v7.2.0)

🗄️ 数据库配置

  • 新增 Prisma + PostgreSQL 集成
  • 创建认证表: user, account, session, verification
  • 配置 DATABASE_URL 环境变量

🛣️ API 路由

  • 移除 [...nextauth] 路由
  • 新增 [...all] 路由,使用 toNextJsHandler

💻 客户端迁移

NextAuth v4 Better-Auth
useSession() authClient.useSession()
status === 'loading' isPending
status === 'unauthenticated' !session
signIn('github') authClient.signIn.social({ provider: 'github' })
signOut() authClient.signOut()

🔧 组件更新

  • ❌ 移除 SessionProvider (不再需要)
  • UserAvatar - 迁移到 authClient.useSession()
  • HeroSection - 迁移到 authClient.useSession()
  • SignIn 页面 - 使用 authClient.signIn.social()
  • ✅ Dashboard 页面 - 迁移到 authClient.useSession()
  • ✅ Dashboard Layout - 修复 await authOptions bug,改用 auth.api.getSession()

⚙️ 配置变更

// 新增 Better-Auth 高级配置
advanced: {
  cookiePrefix: 'telos',
  skipTrailingSlashes: true,  // 支持 Next.js trailingSlash
}

📋 迁移步骤

  1. ✅ 安装 better-auth 和相关依赖
  2. ✅ 配置 Prisma + PostgreSQL
  3. ✅ 创建数据库表
  4. ✅ 替换服务端配置 (auth.ts)
  5. ✅ 替换 API 路由
  6. ✅ 创建客户端配置 (auth-client.ts)
  7. ✅ 移除 SessionProvider
  8. ✅ 更新所有使用认证的组件
  9. ✅ 修复 Dashboard Layout 的 bug
  10. ✅ 添加 skipTrailingSlashes 配置

⚠️ Breaking Changes

  • Cookie 格式变化: Better-Auth 使用不同的 cookie 格式
  • 用户数据: NextAuth 未持久化,用户需重新登录
  • API 路由: 从 /api/auth/[...nextauth] 改为 /api/auth/[...all]
  • 客户端 API: 所有 useSession() 调用需改为 authClient.useSession()

🔍 测试检查清单

  • GitHub OAuth 登录流程
  • Session 持久化(刷新页面后保持登录)
  • 登出功能
  • 受保护页面重定向
  • 数据库记录正确创建

📚 文档


Co-Authored-By: Claude Opus 4.5 noreply@anthropic.com

indulgeback and others added 8 commits January 21, 2026 14:36
BREAKING CHANGE: Complete migration from NextAuth v4 to Better-Auth

### Auth Library Changes
- Replace next-auth with better-auth (v1.4.16)
- Replace @auth/core with better-auth/adapters/prisma
- Add @prisma/adapter-pg for Prisma 7 PostgreSQL driver

### Database Setup
- Add Prisma with PostgreSQL adapter
- Create auth tables: user, account, session, verification
- Configure DATABASE_URL for local development

### API Routes
- Replace [...nextauth] route with [...all] for Better-Auth
- Add toNextJsHandler adapter for Next.js App Router

### Client Changes
- Remove SessionProvider (no longer needed)
- Replace useSession() with authClient.useSession()
- Update signIn/signOut to use authClient methods
- Add auth-client.ts with createAuthClient configuration

### Component Updates
- UserAvatar: migrate to authClient.useSession()
- HeroSection: migrate to authClient.useSession()
- Signin page: use authClient.signIn.social()
- Dashboard pages: migrate to authClient.useSession()
- Dashboard layout: fix authOptions bug, use auth.api.getSession()

### Configuration
- Add skipTrailingSlashes: true for Better-Auth advanced config
- Add basePath: /api/auth and secret for Better-Auth
- Configure cookiePrefix: 'telos'

### Migration Docs
- Add docs/migrate-to-better-auth.md with migration guide
- Add docs/known-issues-better-auth-nextjs-trailing-slash.md

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
### Security Improvements
- Remove hardcoded database credentials from db.ts and prisma.config.ts
- Add production-safe secret validation in auth.ts
  - Throw error if BETTER_AUTH_SECRET not set in production
  - Show warning when using default dev secret

### Feature Improvements
- Restore callbackURL parameter in signin page for custom redirects
- Default callback URL changed from '/' to '/dashboard'

### Documentation
- Add .env.example with comprehensive environment variable guide
  - Required vs optional variables
  - Development and production configuration examples
  - GitHub OAuth app setup instructions
  - Security best practices

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add a mock DATABASE_URL environment variable to prevent potential
build issues in CI when Prisma or Better Auth validates configuration.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add a mock BETTER_AUTH_SECRET to prevent build warnings in CI.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@indulgeback indulgeback merged commit 582ca97 into main Jan 21, 2026
3 checks passed
@indulgeback indulgeback deleted the feat/migrate-to-better-auth branch March 20, 2026 02:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant