Skip to content

Authentication using Better Auth in NuxSaaS

NuxSaaS employs Better Auth, a comprehensive authentication solution for Nuxt.js applications. This document details how NuxSaaS integrates Better Auth to provide secure and flexible user authentication, and why this approach was chosen.

How NuxSaaS Implements Better Auth

Better Auth is configured primarily within server/utils/auth.ts. This central file defines the authentication strategies, database adapters, email handling, and hooks.

Key Implementation Details:

  1. Core Configuration (server/utils/auth.ts):

    • Database Adapter: Uses drizzleAdapter to connect Better Auth with the Drizzle ORM and PostgreSQL database. The schema for authentication-related tables (like user, account, session, verification) is located in server/database/schema/auth.ts.
    • Email & Password: Enabled with email verification required. It defines how reset password and verification emails are sent, integrating with an email service (e.g., Resend, configured via runtimeConfig).
    • Social Providers: Configured for OAuth with providers like GitHub and Google. Client IDs and secrets are managed through runtimeConfig.
    • Hooks: Implements after hooks for audit logging. Successful and failed authentication attempts, password resets, and email verifications are logged using logAuditEvent.
    • Plugins: Integrates Better Auth plugins like admin() for potential admin functionalities and setupStripe() for linking authentication with Stripe billing.
    typescript
    // Snippet from server/utils/auth.ts
    const createBetterAuth = () => betterAuth({
      baseURL: runtimeConfig.public.baseURL,
      secret: runtimeConfig.betterAuthSecret,
      database: drizzleAdapter(
        getDB(),
        {
          provider: 'pg',
          schema
        }
      ),
      // ... other configurations like emailAndPassword, socialProviders, hooks
    });
  2. Session Fetching (app/plugins/auth.server.ts and app/plugins/auth.client.ts):

    • On the server-side (auth.server.ts), the session is fetched during the initial request if the page is server-rendered and not cached, ensuring user state is available immediately.
    • On the client-side (auth.client.ts), session fetching occurs if the page wasn't server-rendered or if it was prerendered/cached to avoid hydration mismatches and ensure the client is synchronized with the auth state.
  3. Route Protection (server/middleware/1.auth.ts and app/middleware/auth.global.ts):

    • Server-side middleware (1.auth.ts) protects API routes like /api/admin/**, ensuring only authenticated users with an 'admin' role can access them. It uses requireAuth from server/utils/auth.ts.
    • Global client-side middleware (auth.global.ts) handles page-level route protection. It checks authentication status and redirects users based on route metadata (e.g., auth: true for protected pages, guest: true for pages only accessible to unauthenticated users).
  4. Composable (app/composables/useAuth.ts):

    • A custom composable useAuth() likely wraps Better Auth's client-side utilities, providing a convenient way to access session state, sign-in/sign-out functions, etc., throughout the Vue components.
  5. Database Schema (server/database/schema/auth.ts):

    • This file defines the Drizzle ORM schema for tables required by Better Auth, such as user, account, and verification. These tables store user credentials, linked social accounts, and email verification tokens.

Why Better Auth?

  • Extensible: Supports various authentication strategies (OAuth, email/password, credentials) and allows for custom providers.
  • Secure by Default: Implements best practices for security, such as CSRF protection and secure session management.
  • Database Agnostic (via Adapters): While NuxSaaS uses Drizzle with PostgreSQL, Better Auth supports multiple database adapters, offering flexibility.
  • Server-Side and Client-Side Utilities: Provides comprehensive tools for both backend authentication logic and frontend session management.
  • Active Community and Development: Being a popular choice for Nuxt authentication, it benefits from ongoing development and community support.

By using Better Auth, NuxSaaS provides a robust, secure, and developer-friendly authentication system that can be easily maintained and extended.