Authentication with Better Auth
Relevant source files
The following files were used as context for generating this wiki page:
TREAD Talks implements authentication using Better Auth integrated with Convex and Next.js. The system handles user registration, session management, role-based access control (RBAC), and secure server-side data fetching. It uses a combination of client-side hooks for interaction and server-side utilities for secure operations and page guards.
Sources: README.md:5-10, convex/auth.ts:1-10
System Architecture
The authentication architecture spans the frontend (Next.js), the backend (Convex), and the database. Better Auth acts as the orchestrator, while the @convex-dev/better-auth plugin connects it to the Convex database and function runtime.
High-Level Authentication Flow
The following diagram illustrates how a user request flows through the Next.js server to the Convex backend using authenticated credentials.
Server-Side Integration
Server-side authentication is managed through src/services/auth/server.ts. This module provides utilities to retrieve the current user, validate sessions, and enforce route guards.
Authentication Utilities
| Utility | Description |
|---|---|
getCurrentUser | Retrieves the authenticated user object or returns null. |
getAuthToken | Retrieves the JWT token for the current session. |
requireCurrentUser | Validates authentication and redirects to login if failed. |
requireAdminUser | Validates authentication and admin role, redirecting if unauthorized. |
fetchAuthQuery | Executes a Convex query with authenticated context. |
fetchAuthMutation | Executes a Convex mutation with authenticated context. |
Sources: src/services/auth/server.ts:40-100
Security Guards
Server Actions and Layouts use guards to restrict access to sensitive operations. For example, creating a talk requires an admin role check before proceeding with data validation.
export async function createTalkAction(data: unknown) {
// Re-verify authorization on every request
await requireAdminUser();
// ... rest of implementation
}
Sources: src/features/talks/actions/create-talk.ts:22-24, src/services/auth/server.ts:85-105
Backend Implementation (Convex)
The Convex backend uses a dedicated Better Auth instance configured in convex/auth.ts. It includes plugins for role management, rate limiting, and CAPTCHA verification via Cloudflare Turnstile.
Better Auth Configuration
The system defines createAuthOptions to configure the authentication behavior:
- Database: Uses
authComponent.adapter(ctx)to store auth data in Convex tables. - Plugins: Includes
adminPluginfor roles,convexPluginfor backend integration, andauthRateLimitPlugin. - Security: Enforces
useSecureCookiesif theSITE_URLstarts with HTTPS. - Trusted Origins: Restricts requests to specific domains like
gettreadtalks.comandlocalhost.
Sources: convex/auth.ts:110-150, convex/auth.ts:35-45
User Management Mutations
User-related operations are handled via Convex mutations that interact with the Better Auth API.
Client-Side Interaction
The authClient provided in src/services/auth/client.ts is the primary interface for user-driven auth events like signing in or resetting passwords.
Authentication Functions
signUp: Registers a new user with email, name, and password. It supports passing an optionalx-captcha-responseheader for bot protection.signIn: Authenticates a user using email and password.signOut: Ends the current session.requestPasswordReset: Triggers a password reset email via the Better Auth server.
Sources: src/services/auth/client.ts:32-75
CAPTCHA and Rate Limiting
The system protects sensitive endpoints from abuse using rate limiting and CAPTCHA.
- Rate Limiting: Applied via
authRateLimitPlugin(ctx)to prevent brute-force attacks. - CAPTCHA: Configured for
/request-password-resetand/sign-up/emailendpoints using Cloudflare Turnstile. - Environment Validation: The system warns if
TURNSTILE_SECRET_KEYis missing in production, which would cause signup and reset requests to fail.
Sources: convex/auth.ts:70-108, convex/auth.ts:98-105
Summary
Authentication is a multi-layered system combining Better Auth's flexibility with Convex's real-time backend. It ensures security through server-side guards (requireAdminUser), environment validation, and robust plugin support for roles and rate limiting. Client interactions are simplified through a standardized authClient, while backend consistency is maintained via the Convex adapter.