Backend changes: - Add better-auth and pg packages - Create Better Auth instance with PostgreSQL adapter - Add Better Auth route handler at /api/auth/* - Create migration script for Better Auth database schema - Update main index to use Better Auth routes instead of custom auth - Configure email/password and OAuth (GitHub/Google) providers Frontend changes: - Add better-auth client - Create Better Auth client instance configuration - Update lib/auth.ts to use Better Auth session - Rewrite sign-in page with Better Auth methods - Rewrite sign-up page with Better Auth methods - Remove NextAuth route handler Documentation: - Add comprehensive migration guide with setup instructions - Document environment variables and API endpoints - Include testing checklist and rollback plan Benefits: - Unified authentication for both Elysia backend and Next.js frontend - Database-backed sessions (more secure than JWT) - Better TypeScript support - Extensible plugin system for future features - Active development and frequent updates
5.3 KiB
5.3 KiB
Better Auth Migration
Overview
Migrated from NextAuth v5 (beta) to Better Auth for unified authentication across both Elysia (backend) and Next.js (frontend).
Backend Changes
Installation
- Added
better-auth@1.4.18package - Added
pg@8.18.0for PostgreSQL connection pool
New Files
backend/src/auth.ts- Better Auth instance configurationbackend/src/routes/better-auth.ts- Route handler for auth endpointsbackend/src/better-auth-migrate.ts- Database migration script
Modified Files
backend/src/index.ts- Replaced custom auth routes with Better Auth routes- Removed custom JWT-based authentication routes (
backend/src/routes/auth.tscan be deleted after migration)
Database Schema
New tables added:
session- Session managementaccount- OAuth/credential account storageverification- Email verification tokens
Existing users table extended with:
email_verified(BOOLEAN)image(TEXT)
Migration Steps
-
Run the migration script:
cd backend bun run src/better-auth-migrate.ts -
Set environment variables:
BETTER_AUTH_SECRET=<generate with: openssl rand -base64 32> BETTER_AUTH_URL=http://localhost:3001
Frontend Changes
Installation
- Added
better-authpackage (includes React client)
New Files
frontend/lib/better-auth.ts- Better Auth client instance
Modified Files
frontend/lib/auth.ts- Updated to use Better Auth sessionfrontend/app/auth/signin/page.tsx- Updated to use Better Auth methodsfrontend/app/auth/signup/page.tsx- Updated to use Better Auth methods- Removed
frontend/app/api/auth/[...nextauth]/route.ts- No longer needed
Authentication Methods
Better Auth supports:
- Email/password (
signIn.email,signUp.email) - OAuth providers (
signIn.social):- GitHub (
signIn.social({ provider: 'github' })) - Google (
signIn.social({ provider: 'google' }))
- GitHub (
Session Management
import { useSession } from '@/lib/better-auth';
// In client components
const { data: session } = useSession();
import { authClient } from '@/lib/better-auth';
// In server components
const { data: session } = await authClient.getSession();
Environment Variables
Required
# Backend
DATABASE_URL=postgres://user:password@localhost:5432/fiscal
BETTER_AUTH_SECRET=<32+ character random string>
BETTER_AUTH_URL=http://localhost:3001
# OAuth Providers
GITHUB_ID=<your github client id>
GITHUB_SECRET=<your github client secret>
GOOGLE_ID=<your google client id>
GOOGLE_SECRET=<your google client secret>
# Frontend
NEXT_PUBLIC_API_URL=http://localhost:3001
API Endpoints
Better Auth provides these endpoints automatically (mounted at /api/auth/*):
Email/Password
POST /api/auth/sign-up/email- Sign up with emailPOST /api/auth/sign-in/email- Sign in with emailGET /api/auth/get-session- Get current sessionPOST /api/auth/sign-out- Sign out
OAuth
GET /api/auth/sign-in/social- Initiate OAuth flowGET /api/auth/callback/*- OAuth callback handler
Session
GET /api/auth/get-session- Get current sessionPOST /api/auth/update-session- Update session data
Key Differences from NextAuth
NextAuth
- Configuration in route handler (
app/api/auth/[...nextauth]/route.ts) - Server-side session management with JWT
- Custom callback for session/user data
- Requires
signIn()andsignOut()fromnext-auth/react
Better Auth
- Configuration in separate file (
backend/src/auth.ts) - Server and client components unified API
- Built-in session management with database storage
signIn.email,signIn.social,signOutfrombetter-auth/react- Direct database access for user/session data
Testing Checklist
- Run database migration:
bun run src/better-auth-migrate.ts - Start backend server
- Test email/password signup
- Test email/password login
- Test GitHub OAuth
- Test Google OAuth
- Test sign out
- Test protected routes redirect to sign in
- Test session persistence across page refreshes
Rollback Plan
If issues arise, revert to NextAuth:
- Restore
frontend/app/api/auth/[...nextauth]/route.ts - Restore
frontend/app/auth/signin/page.tsxandfrontend/app/auth/signup/page.tsx - Restore
frontend/lib/auth.ts - Remove
backend/src/auth.tsandbackend/src/routes/better-auth.ts - Restore custom auth routes in backend
Benefits of Better Auth
- Unified Auth - Single auth system for both backend and frontend
- Type Safety - Better TypeScript support
- Database-Backed Sessions - More secure than JWT
- Extensible - Plugin system for 2FA, email verification, etc.
- Active Development - More frequent updates and improvements
- Framework Agnostic - Works with any backend framework
Future Improvements
- Enable email verification (Better Auth plugin)
- Add two-factor authentication (Better Auth plugin)
- Implement account management (password reset, email change)
- Add session management UI (view active sessions, revoke)
- Implement role-based access control (Better Auth plugin)
Resources
- Better Auth Docs: https://www.better-auth.com/
- Better Auth GitHub: https://github.com/better-auth/better-auth
- Migration Guide: https://www.better-auth.com/docs/migration