Nuxt Better Auth Utilities

0.1.27 · active · verified Wed Apr 22

nuxt-better-auth-utils is a Nuxt module providing a full lifecycle integration for the Better Auth library, offering auto-wired API handlers, SSR session pre-fetching, and typed server/client APIs. It's currently at version 0.1.27 and has a rapid release cadence with frequent bug fixes and minor improvements, often multiple releases per week. Key differentiators include its tight integration with Nuxt's SSR capabilities, providing reactive session state via `useAuth()` on the client and `useServerAuth()` for server-side operations, and automatic type inference. It remains database-agnostic, deferring to Better Auth's adapter ecosystem. This module aims to simplify authentication setup in Nuxt applications by handling much of the boilerplate, including API routing, session management, and protecting pages with middleware, without imposing opinions on the underlying authentication strategy or data storage.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core setup of nuxt-better-auth-utils, including Nuxt module configuration, defining server and client authentication configurations, and using the `useAuth()` composable and `auth` middleware to protect a page. It illustrates integration with a hypothetical Drizzle database adapter.

import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { organization } from 'better-auth/plugins';
import { defineDrizzleConfig, useDrizzle } from '#nuxt-drizzle'; // Assuming nuxt-drizzle for DB

// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    'nuxt-better-auth-utils',
    '#some-database-module' // e.g., 'nuxt-drizzle'
  ],
  betterAuthUtils: {
    redirectTo: '/login',
  },
  // Configure other modules like nuxt-drizzle if used
  // drizzle: { ... }
});

// server/auth.server.config.ts
// Ensure database client is available via your preferred Nuxt database module.
// This example assumes `useDrizzle()` from `nuxt-drizzle`.
export default defineAuthConfig(() => {
  // In a real application, replace useDrizzle with your actual database client setup
  const db = useDrizzle(); // Example using a hypothetical nuxt-drizzle hook
  return {
    database: drizzleAdapter(db, { provider: 'pg' }), // Replace with your adapter
    emailAndPassword: { enabled: true },
    plugins: [organization()],
  };
});

// app/auth.client.config.ts
import { organizationClient } from 'better-auth/client/plugins';
export default defineAuthClientConfig({
  plugins: [organizationClient()],
});

// pages/protected.vue
<script setup lang="ts">
definePageMeta({
  middleware: 'auth',
});
const { session, user, loggedIn, signOut } = useAuth();
</script>

<template>
  <div>
    <h1>Welcome, {{ user?.email }}!</h1>
    <p v-if="loggedIn">You are logged in.</p>
    <button @click="signOut({ redirectTo: '/login' })">Sign Out</button>
  </div>
</template>

view raw JSON →