Better Auth User Module Consolidation
Overview
The Bun backend’s user module has been consolidated to delegate all authentication and user lifecycle operations directly to Better Auth’s server API. This eliminates redundant custom code, simplifies the codebase, and provides a single source of truth for user management.Architecture Decision
Previously, the system maintained parallel implementations:- Custom domain layer:
RegisterUserUseCase,LoginUserUseCase,UpdateUserProfileUseCase,GetUserUseCase - Custom repository: MongoDB-based
UserRepositoryfor persistence - Custom password handling:
PasswordServicewith custom hashing logic
authPort, with route handlers calling these APIs transparently.
Updated Component Model
Before Consolidation
After Consolidation
Core Components
1. authPort (Ports)
Defined in@bun-core/auth-ports, the minimal interface for authentication operations:
authPort methods call Better Auth’s server API directly. No custom use cases between route and API.
2. Better Auth Adapter
Defined in@bun-core/auth-adapter, the adapter bridges route handlers to Better Auth:
3. Route Handlers
Route handlers callauthPort directly without intermediate use cases:
4. Admin & Organization APIs
For user management operations (update profile, get user, manage organization roles), use Better Auth’s admin plugin:Database Schema
Better Auth manages these PostgreSQL tables:
Key point: All these tables are owned and managed by Better Auth. No custom migration scripts needed.
Role Management
Platform Roles
Platform-level roles (user, admin, etc.) are stored in theusers.role column from Better Auth’s admin plugin:
Organization Roles
Organization-specific roles (owner, admin, member, staff, viewer) are managed via themembers table:
Authentication Flow
Registration
- Client Request:
POST /api/v1/users/register { email, password } - Route Handler: Calls
authPort.signUp.email({ email, password }) - Better Auth:
- Validates email uniqueness
- Hashes password with scrypt
- Creates
authrecord - Creates
accountsrecord with password hash - Returns user + session token
- Response: Returns JWT and user data
Login
- Client Request:
POST /api/v1/users/login { email, password } - Route Handler: Calls
authPort.signIn.email({ email, password }) - Better Auth:
- Queries
authtable by email - Fetches password hash from
accounts - Verifies password (scrypt)
- Creates session if valid
- Returns user + JWT
- Queries
- Response: Returns JWT and user data
User Retrieval
- Route Handler:
GET /api/v1/users/me - Middleware: Extracts JWT, verifies, attaches user to context
- Handler: Calls
auth.api.getUser({ query: { id: userId } }) - Better Auth: Returns user data from
authtable - Response: Returns user with platform role
Profile Update
- Client Request:
PATCH /api/v1/users/me { name, image } - Route Handler: Calls
auth.api.adminUpdateUser({ body: { userId, data } }) - Better Auth: Updates
authtable, returns updated user - Response: Returns updated user data
Password Hashing
Better Auth uses scrypt for password hashing (Better Auth default).Related Components
Key Takeaways
- Simplified code: No custom use cases, repositories, or password logic
- Single source of truth: Better Auth owns all user state in PostgreSQL
- Direct delegation: Route handlers call Better Auth API directly via
authPort - Clean separation: Better Auth handles persistence, adapters handle bridging, routes handle HTTP
Removed Components
- ❌
RegisterUserUseCase(now directauthPort.signUp.email()call) - ❌
LoginUserUseCase(now directauthPort.signIn.email()call) - ❌
UpdateUserProfileUseCase(now directauth.api.adminUpdateUser()call) - ❌
GetUserUseCase(now directauth.api.getUser()call) - ❌
UserRepositoryMongoDB implementation (Better Auth handles persistence) - ❌
PasswordService(Better Auth owns password hashing) - ❌ Custom password hashing logic (scrypt via Better Auth)
Next Steps & Future Phases
Phase 2: Email Infrastructure
- Implement email service (SMTP or third-party)
- Enable email verification: set
requireEmailVerification: true - Implement forgot password flow via
auth.api.recoveryEmail() - Implement password reset flow
Phase 3: Advanced Features
- Two-factor authentication (Better Auth has
2faplugin) - User deactivation (add
isActivecolumn toauthtable if needed) - Session management API
- Role-based access control (RBAC) enforcement
- Audit logging for auth events