M
Melvynx
#Clerk#Better Auth#Authentication

Clerk vs Better Auth: Choosing the Right Authentication for Your SaaS

Compare Clerk and Better Auth for SaaS authentication, focusing on vendor lock-in, customization, and cost. Learn why owning your auth with a TypeScript library can be more beneficial than relying on external services for long-term product control.

5 min readAI Guide

Introduction

Clerk is a comprehensive authentication and user management service that offers a premium experience with rapid integration, hosted services, an SDK, and a dashboard. Better Auth is a TypeScript library designed for self-hosted authentication, providing full control over the user model, flows, and product integration within your application and database.

Configuration Checklist

Element Version / Link
Language / Runtime TypeScript, Next.js, React, Mobile, APIs
Main library Clerk, Better Auth
Required APIs Clerk's proprietary APIs, Better Auth's API (self-hosted)
Keys / credentials needed Clerk API keys (for external service), Database credentials (for Better Auth)

Step-by-Step Guide

The video primarily showcases the features and dashboards of Clerk and a custom implementation using Better Auth (NowStack) rather than providing explicit step-by-step installation or configuration instructions. Below is a description of the functionalities demonstrated.

Clerk Dashboard Overview

Clerk provides a dashboard for managing applications, users, and organizations. The speaker demonstrates navigating through these sections.

  1. Applications: Create and manage different applications.
  2. Users: View and manage user sign-ups, including email addresses and join dates.
  3. Organizations: Manage organizations, including member activity, organization information (name, logo, slug), enterprise connections, and metadata (public/private).
  4. Settings: Configure various aspects of the workspace, including billing and usage.

Better Auth (NowStack) Dashboard Overview

The speaker presents a custom dashboard built with Better Auth, replicating and extending Clerk's functionalities.

  1. Authentication Pages: Fully customizable sign-in, sign-up, and password reset pages.

    // [Editor's note: Actual code for these pages is not shown, but implied to be custom React/Next.js components]
    // Example structure for a sign-in component with Better Auth
    import { signIn } from 'better-auth';
    import React, { useState } from 'react';
    
    function SignInForm() {
      const [email, setEmail] = useState('');
      const [password, setPassword] = useState('');
    
      const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
          await signIn(email, password); // Better Auth signIn function
          // Redirect on success
        } catch (error) {
          // Handle error
        }
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" />
          <button type="submit">Sign In</button>
          {/* Other options like OTP, Google/GitHub sign-in */}
        </form>
      );
    }
    
  2. Admin Dashboard: A custom-built admin interface mirroring Clerk's dashboard features.

    • Users: View user profiles, including avatar, name, email, social accounts, password, devices, and metadata. User activity graphs (similar to GitHub) are mentioned but not implemented in the demo for data storage reasons.
    • Organizations: Manage organizations, including members, invitations, roles (admin, owner, member), and API keys.
    • Billing: Integrated billing management.
    • Settings: Organization settings, including logo upload and name.
    // [Editor's note: Actual code for the admin dashboard components is not shown, but implied to be custom React/Next.js components interacting with Better Auth's API]
    // Example of promoting a user to admin role via Better Auth API
    import { updateRole } from 'better-auth/admin'; // Assuming an admin API
    
    async function promoteUserToAdmin(userId: string, organizationId: string) {
      try {
        await updateRole(userId, organizationId, 'admin');
        console.log('User promoted to admin successfully');
      } catch (error) {
        console.error('Failed to promote user:', error);
      }
    }
    

Better Auth Plugins

Better Auth offers a wide range of plugins for various authentication, authorization, payments, security, and utility features.

  • Authentication: Two-Factor Authentication, Passkey, Magic Link, Email OTP, Phone Number, Anonymous, Username, One Tap, Sign In With Ethereum, Generic OAuth, Multi Session, Last Login Method.

  • Authorization & Management: Admin, Organization, SSO, SCIM.

  • API & Tokens: Agent Auth, API Key, JWT, Bearer, One-Time Token, OAuth Proxy.

  • Payments & Billing: Stripe, Polar, Autumn Billing, Cream, Dodo Payments.

  • Security & Utilities: Captcha, Have I Been Pwned, i18n, Open API, Test Utils.

  • Analytics & Tracking: Dub (Lead tracking).

    // [Editor's note: Specific installation commands for each plugin are not provided in the video. Refer to Better Auth documentation for details.]
    // Example: Integrating a plugin (conceptual)
    // npm install better-auth-plugin-2fa
    // import { TwoFactorAuthPlugin } from 'better-auth-plugin-2fa';
    // BetterAuth.use(TwoFactorAuthPlugin);
    

Comparison Tables

Comparison Tables

Comparison Tables

Clerk vs Better Auth

Feature Clerk Better Auth
Experience Premium, quick to integrate Flexible, requires custom UI
Hosting Hosted service Self-hosted (in your app)
SDK/Dashboard Provided SDK + dashboard TypeScript library, custom dashboard (NowStack)
Data Control External user data, metadata, webhooks User data in your DB, direct relations, simple queries
Product Control Limited customization, visual limits Full control over user model and flows
Lock-in High vendor lock-in Low vendor lock-in

Value vs Lock-in Matrix

Quadrant Freedom (Low Lock-in) Lock-in (High Lock-in)
Value++ (High Value) Tanstack Start Convex, Vercel, Next.js
Value-- (Low Value) PostgreSQL, Prisma Clerk

Clerk Components vs Better Auth + Your UI

Clerk Components Better Auth + Your UI
Super rapid integration Native design system
Less theme/appearance control Controlled copy
Visual limits Custom flows
Custom flows (if needed) No mental iframe

Le coût caché: migrer l'auth

Le coût caché: migrer l'auth
Changing an authentication tool is not like changing a button; it affects the entire application. The Auth provider is the central node (le nœud central) that connects to various parts of your application, including:

  • Middleware: Handles authentication logic before requests reach your routes.
  • API routes: Secures your API endpoints.
  • DB user: Manages user data in your database.
  • UI: Controls the user interface for login, signup, etc.
  • Billing: Integrates with user authentication for subscription management.

This deep integration means that switching authentication providers can be a complex and costly process, leading to significant vendor lock-in. It's acceptable if the value provided is substantial; otherwise, it's just a hidden cost.

⚠️ Common Mistakes & Pitfalls

  1. Underestimating Vendor Lock-in: Relying heavily on external authentication services like Clerk can lead to significant vendor lock-in, making it difficult and costly to migrate to another solution or customize beyond the provider's offerings. This is especially true for core functionalities like authentication that touch every part of your application.
  2. High Costs for Basic Features: Some external authentication services charge premium prices for features that can be easily implemented or are included for free in self-hosted solutions. For example, Clerk charges for impersonating users or B2B authentication features, which can quickly add up.
  3. Limited UI/UX Customization: While external services offer pre-built UI components, they often come with limitations on theming, appearance, and custom flows. This can prevent your authentication experience from seamlessly matching your product's brand and user experience.
  4. Data Ownership and Control: When using external auth providers, your user data resides on their servers. This can complicate data management, compliance, and direct integration with your product's core logic, forcing you to use metadata fields or webhooks for synchronization.
  5. Vibe Coding: Relying solely on AI to generate code without a solid architectural foundation (like NowStack) can lead to applications that are buggy, hard to maintain, and not scalable. A structured boilerplate ensures quality and maintainability even with AI assistance.

Glossary

Vendor Lock-in: A situation where a customer is dependent on a vendor for products and services and cannot switch to another vendor without substantial costs, effort, or technical changes.
SaaS: Software as a Service, a software distribution model in which a third-party provider hosts applications and makes them available to customers over the Internet.
Boilerplate: A reusable set of code, configurations, and assets that provides a starting point for new projects, often including common functionalities like authentication, database setup, and UI components.

Key Takeaways

  • Prioritize Data Ownership: Internalizing your authentication (e.g., with Better Auth) gives you full control over user data, relations, and product logic, avoiding external dependencies.
  • Beware of Hidden Costs: While external services like Clerk offer quick setup, they can introduce high costs for advanced features (e.g., impersonation, B2B multi-tenancy) and long-term vendor lock-in.
  • Customization is Key: For a unique product experience, full control over authentication UI/UX and flows is crucial, which is often limited by external providers' pre-built components.
  • Auth is Product: Authentication is not just a login screen; it quickly integrates with onboarding, billing, roles, and invites, becoming a core part of your product's business logic.
  • Leverage AI for Internalization: AI agents can significantly accelerate the development of custom authentication features and dashboards, making self-hosting a more viable and efficient option for small teams.
  • Choose Wisely Based on Value: Evaluate whether the value an external service provides (e.g., quick shipping) outweighs the long-term costs and limitations of vendor lock-in, especially for core functionalities.
  • NowStack as an Alternative: NowStack offers a simple, cost-effective, and AI-native boilerplate that internalizes authentication and other critical SaaS features, providing flexibility and control.

Resources