
๐ What is Better Auth?
Better Auth is a modern, open-source authentication and authorization framework designed for the TypeScript ecosystem. It provides a comprehensive set of features out of the box, including support for email/password authentication, social sign-on (OAuth), two-factor authentication (2FA), multi-tenancy, and more. Better Auth is framework-agnostic, meaning it can be integrated into various TypeScript-based frameworks such as Next.js, SvelteKit, Astro, and TanStack Start .
The primary goal of Better Auth is to simplify the implementation of authentication systems by offering a robust, extensible, and type-safe solution. It allows developers to focus on building their applications without reinventing the wheel when it comes to user authentication and authorization.
๐ผ Major Use Cases of Better Auth
- Secure User Authentication: Implement secure login mechanisms using email/password, social logins (Google, GitHub, Apple, Discord), and more.
- Two-Factor Authentication (2FA): Enhance security by adding an additional layer of authentication, such as SMS or authenticator apps.
- Multi-Tenant Applications: Manage organizations, teams, and access control for applications that serve multiple clients or user groups.
- Session Management: Handle user sessions with features like session expiration, revocation, and multi-session support.
- Custom Authentication Flows: Extend the authentication system with custom plugins to meet specific application requirements.
- Integration with Modern Frameworks: Seamlessly integrate with popular TypeScript frameworks, providing a consistent authentication experience across different platforms.
๐ง How Better Auth Works โ Architecture Overview
Better Auth operates as a backend authentication service that integrates with your application through a simple API. Here’s an overview of its architecture:
๐น Core Components:
- Authentication Providers: Support for various authentication methods, including email/password, OAuth providers (Google, GitHub, etc.), and custom plugins.
- Session Management: Handles user sessions, including creation, expiration, and revocation.
- Database Integration: Utilizes databases like PostgreSQL, MySQL, or SQLite to store user data and session information.
- Plugin System: Allows for the extension of authentication functionalities through custom plugins.
- Rate Limiting: Built-in rate limiter to prevent abuse and ensure fair usage.
- Security Features: Includes features like 2FA, secure password hashing, and protection against common vulnerabilities.
๐น Data Flow:
- User Initiates Authentication: The user attempts to log in through the application interface.
- Authentication Request: The application sends an authentication request to the Better Auth service.
- Credential Verification: Better Auth verifies the provided credentials against the configured authentication providers.
- Session Creation: Upon successful authentication, Better Auth creates a session and returns a session token to the application.
- Access Granted: The application uses the session token to grant the user access to protected resources.
- Session Management: Better Auth manages the session lifecycle, including expiration and revocation.
๐ Basic Workflow of Better Auth
- Installation: Install the Better Auth package using npm or yarn.
npm install better-auth - Configuration: Create an
auth.tsfile and configure Better Auth with your desired authentication methods and database connection.import { betterAuth } from "better-auth"; export const auth = betterAuth({ database: new Pool({ connectionString: DATABASE_URL, }), emailAndPassword: { enabled: true, }, plugins: [ organization(), twoFactor(), ], }); - Session Management: Use the provided API to manage user sessions, including login, logout, and session validation.
const session = await auth.login({ email, password }); - Access Control: Implement access control mechanisms to restrict access to certain resources based on user roles or permissions.
- Extend Functionality: Utilize the plugin system to add custom authentication features as needed.
๐ Step-by-Step Getting Started Guide for Better Auth
โ 1. Install Better Auth
Install the Better Auth package in your project:
npm install better-auth
โ 2. Set Up Database
Configure your database connection. Better Auth supports PostgreSQL, MySQL, and SQLite. For example, using PostgreSQL:
import { Pool } from "pg";
const db = new Pool({
connectionString: process.env.DATABASE_URL,
});
โ 3. Configure Authentication
Create an auth.ts file and configure Better Auth with your desired authentication methods:
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: db,
emailAndPassword: {
enabled: true,
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
},
},
});
โ 4. Implement Authentication Flows
Use the provided API to implement authentication flows in your application:
const session = await auth.login({ email, password });
โ 5. Manage Sessions
Handle session management, including creation, validation, and expiration:
const user = await auth.getSession(sessionToken);
โ 6. Extend Functionality with Plugins
Add custom functionality using the plugin system:
import { twoFactor } from "better-auth/plugins";
auth.use(twoFactor());
โ 7. Deploy and Monitor
Deploy your application and monitor authentication activities using the provided tools and dashboards.