Better Auth - Technical Overview
Better Auth is a comprehensive, open-source authentication and authorization framework for TypeScript. Unlike managed auth services that store user data externally, Better Auth lets developers keep all authentication data in their own database while providing a rich plugin ecosystem for advanced features like organizations, two-factor authentication, and passkeys.
High-Level Architecture
Authentication Flow
Database Schema
Key Concepts
Framework Agnostic Design
Better Auth works with any TypeScript server framework including Next.js, Nuxt, SvelteKit, Remix, Solid Start, Hono, Express, and Elysia. The auth handler mounts at a single endpoint (typically /api/auth/*) and handles all authentication routes.
Plugin Architecture
One of Better Auth's distinguishing features is its plugin system. Complex authentication features like organizations, 2FA, passkeys, and magic links are implemented as plugins that:
- Add their own database tables automatically
- Extend the user/session types
- Expose new API endpoints
- Provide client-side methods
Database Adapters
Better Auth uses Kysely as its default database handler but provides first-class adapters for:
- Prisma: Generates schema.prisma files
- Drizzle: Generates TypeScript schema
- Kysely: Generates SQL migration files
- MongoDB: NoSQL adapter
Session Management
Sessions are stored in your database (not as JWTs by default), giving you full control over:
- Session revocation
- Multi-device session listing
- Session metadata (IP, user agent)
- Custom session expiration
Cookie Security
All cookies are:
httpOnly: Not accessible via JavaScriptSecure: Only sent over HTTPS in productionSameSite=Lax: CSRF protection- Signed with your secret key
Authentication Methods
Plugin Ecosystem
Session Encoding Strategies
Organization & Multi-Tenancy
Technical Details
Server Configuration
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: {
provider: "postgresql", // or mysql, sqlite
url: process.env.DATABASE_URL,
},
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
},
},
plugins: [
twoFactor(),
organization(),
passkey(),
],
});Client Configuration
import { createAuthClient } from "better-auth/client";
export const authClient = createAuthClient({
baseURL: "http://localhost:3000",
plugins: [
twoFactorClient(),
organizationClient(),
passkeyClient(),
],
});Type Safety
Better Auth is fully typed with TypeScript. Use $Infer to get types for users and sessions, including extensions from plugins:
type User = typeof auth.$Infer.Session["user"];
type Session = typeof auth.$Infer.Session["session"];CLI Commands
npx @better-auth/cli generate: Generate database schema for your ORMnpx @better-auth/cli migrate: Apply migrations (Kysely adapter)
Experimental Joins
Since v1.4, Better Auth supports database joins for 50+ endpoints, providing 2-3x performance improvements by reducing database roundtrips.
Framework Integration
Key Facts (2025)
- GitHub Stars: 15,000+ stars on GitHub
- Weekly Downloads: 150,000+ npm weekly downloads
- Discord Community: 6,000+ members
- Initial Release: September 2024
- Funding: $5M seed funding (YC X25)
- License: MIT (fully open source)
- Latest Version: 1.4.x with experimental joins support
- OAuth Providers: 40+ built-in + Generic OAuth for custom providers
- Framework Support: 10+ server frameworks, 5+ client frameworks
- Database Support: PostgreSQL, MySQL, SQLite + any Kysely dialect
- Data Ownership: All user data stays in your database
Use Cases
Startup MVPs
- Quick setup with email/password and social OAuth
- No external service costs or vendor lock-in
- Type-safe API with excellent DX
B2B SaaS Applications
- Multi-tenant organizations out of the box
- Role-based access control (RBAC)
- Custom permissions per organization
- Invitation and member management
Enterprise Applications
- Generic OAuth plugin for Okta, Auth0, Keycloak, Microsoft Entra
- Two-factor authentication (TOTP, SMS, backup codes)
- Session management and audit capabilities
- On-premise data storage requirement compliance
API-First Products
- Bearer token authentication for APIs
- JWT session encoding for microservices
- OpenAPI spec generation
Security-Critical Applications
- Passkey/WebAuthn support for phishing-resistant auth
- JWE encrypted cookies for sensitive data
- Built-in rate limiting
- Cookie signing and validation
Security Considerations
Built-in Protections
- Rate Limiting: Automatic protection against brute-force attacks
- Cookie Security: httpOnly, Secure, SameSite=Lax by default
- Password Hashing: Argon2/bcrypt with secure defaults
- CSRF Protection: State and nonce validation for OAuth callbacks
- Input Validation: Comprehensive validation on all endpoints
Session Security
- Database-backed sessions allow instant revocation
- Optional cookie cache with configurable TTL
disableCookieCache: truefor sensitive operations- Session metadata tracking (IP, user agent)
Best Practices
- Use
BETTER_AUTH_SECRETenvironment variable (32+ characters) - Enable
baseURLconfiguration for production - Use JWE encoding for sensitive session data
- Implement proper CORS configuration
- Monitor authentication events
Comparison to Alternatives
| Feature | Better Auth | NextAuth/Auth.js | Lucia Auth |
|---|---|---|---|
| Data Ownership | Your DB | Your DB | Your DB |
| Plugin System | Extensive | Limited | None |
| TypeScript | Native | Good | Native |
| Organizations | Built-in plugin | External | DIY |
| Passkeys | Built-in plugin | Limited | DIY |
| Maintenance | Active | Active | Deprecated |
Sources
- Better Auth Official Website
- Better Auth Documentation
- Better Auth GitHub Repository
- Better Auth npm Package
- Database Documentation
- Session Management
- Two-Factor Authentication Plugin
- Organization Plugin
- Passkey Plugin
- Magic Link Plugin
- OAuth Documentation
- Cookie Security
- Drizzle Adapter
- Prisma Adapter
- Is Better Auth the key to solving authentication headaches? - LogRocket
- Better Auth vs NextAuth vs Auth0 - Better Stack
- Auth.js vs BetterAuth Comparison - Wisp CMS
- BetterAuth with Encore.ts Guide
- Better Auth YC X25 Funding