# 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.18` package - Added `pg@8.18.0` for PostgreSQL connection pool ### New Files - `backend/src/auth.ts` - Better Auth instance configuration - `backend/src/routes/better-auth.ts` - Route handler for auth endpoints - `backend/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.ts` can be deleted after migration) ### Database Schema New tables added: - `session` - Session management - `account` - OAuth/credential account storage - `verification` - Email verification tokens Existing `users` table extended with: - `email_verified` (BOOLEAN) - `image` (TEXT) ### Migration Steps 1. Run the migration script: ```bash cd backend bun run src/better-auth-migrate.ts ``` 2. Set environment variables: ```env BETTER_AUTH_SECRET= BETTER_AUTH_URL=http://localhost:3001 ``` ## Frontend Changes ### Installation - Added `better-auth` package (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 session - `frontend/app/auth/signin/page.tsx` - Updated to use Better Auth methods - `frontend/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' })`) ### Session Management ```typescript import { useSession } from '@/lib/better-auth'; // In client components const { data: session } = useSession(); ``` ```typescript import { authClient } from '@/lib/better-auth'; // In server components const { data: session } = await authClient.getSession(); ``` ## Environment Variables ### Required ```env # 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= GITHUB_SECRET= GOOGLE_ID= GOOGLE_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 email - `POST /api/auth/sign-in/email` - Sign in with email - `GET /api/auth/get-session` - Get current session - `POST /api/auth/sign-out` - Sign out ### OAuth - `GET /api/auth/sign-in/social` - Initiate OAuth flow - `GET /api/auth/callback/*` - OAuth callback handler ### Session - `GET /api/auth/get-session` - Get current session - `POST /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()` and `signOut()` from `next-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`, `signOut` from `better-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: 1. Restore `frontend/app/api/auth/[...nextauth]/route.ts` 2. Restore `frontend/app/auth/signin/page.tsx` and `frontend/app/auth/signup/page.tsx` 3. Restore `frontend/lib/auth.ts` 4. Remove `backend/src/auth.ts` and `backend/src/routes/better-auth.ts` 5. Restore custom auth routes in backend ## Benefits of Better Auth 1. **Unified Auth** - Single auth system for both backend and frontend 2. **Type Safety** - Better TypeScript support 3. **Database-Backed Sessions** - More secure than JWT 4. **Extensible** - Plugin system for 2FA, email verification, etc. 5. **Active Development** - More frequent updates and improvements 6. **Framework Agnostic** - Works with any backend framework ## Future Improvements 1. Enable email verification (Better Auth plugin) 2. Add two-factor authentication (Better Auth plugin) 3. Implement account management (password reset, email change) 4. Add session management UI (view active sessions, revoke) 5. 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