Overview
The authentication system handles:- User account creation and management
- Email and password authentication
- Session management with secure cookies
- Email verification
- Cross-platform support (web + mobile via Expo)
- Integration with PostgreSQL via Drizzle ORM
Better-Auth Configuration
Implementation:/home/daytona/workspace/source/apps/web/src/lib/auth.ts:8
Key Configuration Options
Database Adapter
Database Adapter
Better-Auth uses the Drizzle adapter to connect to PostgreSQL:This automatically handles all database operations for authentication, including user creation, session management, and verification tokens.
Trusted Origins
Trusted Origins
Expo mobile app support requires This allows the React Native app to authenticate against the same backend.
exp:// in trusted origins:Cookie Settings
Cookie Settings
Additional User Fields
Additional User Fields
The This allows storing Canvas credentials and other user-specific configuration.
settings field is added as a custom user field:Database Schema
Implementation:/home/daytona/workspace/source/apps/web/src/db/schema/auth.ts:4
The authentication system uses four database tables:
User Table
id: Primary key (text-based UUID)email: Unique identifier for loginemailVerified: Whether the email has been verifiedsettings: JSONB column for flexible user configuration (Canvas credentials, preferences, etc.)
Session Table
- Unique session tokens for each login
- IP address and user agent tracking
- Automatic expiration timestamps
- Cascade delete when user is removed
Sessions are automatically cleaned up when they expire or when the user logs out.
Account Table
- Links users to authentication providers
- Stores OAuth tokens for providers like Google, GitHub, etc.
- Stores hashed passwords for email/password authentication
- Supports multiple authentication methods per user
Verification Table
- Email verification tokens
- Password reset tokens
- Magic link authentication
- Automatic expiration of tokens
User Authentication Flow
Maxw AI implements a standard authentication flow with Better-Auth:User Registration
User provides email and password. Better-Auth hashes the password and creates:
- User record in
usertable - Account record in
accounttable with hashed password - Verification token in
verificationtable
Email Verification
A verification email is sent with a unique token. When the user clicks the link:
- Token is validated against
verificationtable emailVerifiedis set totrueinusertable- Verification token is deleted
User Login
User submits email and password:
- Better-Auth looks up the user by email
- Password is verified against the hashed version
- A new session is created in
sessiontable - Session token is stored in a secure HTTP-only cookie
Session Management
On each request:
- Session token is extracted from the cookie
- Token is validated against
sessiontable - User data is retrieved and attached to the request
- Session expiration is checked
Session Management
Sessions are managed using Better-Auth’s built-in session handling:Getting Current Session
Session Properties
Better-Auth automatically handles session renewal and expiration. Sessions are extended on each request, providing a smooth user experience.
API Endpoints
Better-Auth automatically creates API endpoints at/api/auth/*:
POST /api/auth/sign-up/email- Register with email/passwordPOST /api/auth/sign-in/email- Login with email/passwordPOST /api/auth/sign-out- LogoutGET /api/auth/session- Get current sessionPOST /api/auth/verify-email- Verify email addressPOST /api/auth/forgot-password- Request password resetPOST /api/auth/reset-password- Reset password with token
OAuth Providers
While the current configuration only enables email/password authentication, Better-Auth supports OAuth providers:Adding OAuth Providers
Security Features
Password Security
- Passwords are hashed using bcrypt before storage
- Password reset uses time-limited tokens
- Failed login attempts are tracked (if configured)
Session Security
- HTTP-only cookies prevent XSS attacks
- Secure flag ensures HTTPS-only transmission
- SameSite=none allows cross-origin requests while maintaining security
- IP address and user agent tracking for anomaly detection
Token Security
- Verification tokens are single-use
- All tokens have expiration timestamps
- Tokens are cryptographically random
Database Security
- All foreign keys use
onDelete: "cascade"for referential integrity - Automatic timestamp updates prevent stale data
- Email uniqueness constraint prevents duplicate accounts
Environment Variables
Required:Email Verification
Email verification is enabled by default with Better-Auth:- User signs up with email and password
emailVerifiedis set tofalse- Verification email is sent (requires email configuration)
- User clicks verification link
emailVerifiedis updated totrue
Email Configuration
To enable email sending, configure an email provider in Better-Auth:Cross-Platform Support
The Expo plugin enables authentication in the React Native mobile app:- Shared authentication backend for web and mobile
- Deep linking for email verification and password reset
- Secure token storage using platform-specific secure storage
Error Handling
Common authentication errors:Common Error Cases
- Invalid credentials: Wrong email or password
- Email already exists: Duplicate registration attempt
- Session expired: User needs to log in again
- Invalid token: Verification or reset token is invalid or expired
- Email not verified: Some actions may require verified email
Best Practices
- Always validate sessions: Check for valid session before accessing protected resources
- Use environment variables: Never hardcode secrets in your application code
- Implement rate limiting: Protect login endpoints from brute-force attacks
- Log authentication events: Track successful and failed login attempts for security monitoring
-
Secure cookie settings: Always use
secure,httpOnly, and appropriatesameSitesettings in production - Regular token cleanup: Periodically clean up expired tokens and sessions from the database
- Multi-factor authentication: Consider adding 2FA for enhanced security (Better-Auth supports this)
Related Resources
- Better-Auth Documentation: https://better-auth.com
- Drizzle ORM: https://orm.drizzle.team
- Database Migrations: Use
bun db:generateandbun db:migratefor schema changes - Session Management: Sessions are automatically managed by Better-Auth middleware