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:
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 (likeuser
,account
,session
,verification
) is located inserver/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 usinglogAuditEvent
. - Plugins: Integrates Better Auth plugins like
admin()
for potential admin functionalities andsetupStripe()
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 });
- Database Adapter: Uses
Session Fetching (
app/plugins/auth.server.ts
andapp/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.
- On the server-side (
Route Protection (
server/middleware/1.auth.ts
andapp/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 usesrequireAuth
fromserver/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).
- Server-side middleware (
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.
- A custom composable
Database Schema (
server/database/schema/auth.ts
):- This file defines the Drizzle ORM schema for tables required by Better Auth, such as
user
,account
, andverification
. These tables store user credentials, linked social accounts, and email verification tokens.
- This file defines the Drizzle ORM schema for tables required by Better Auth, such as
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.