Socket
Book a DemoInstallSign in
Socket

better-auth-nuxt

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

better-auth-nuxt

Better Auth Nuxt Module

latest
Source
npmnpm
Version
0.0.9
Version published
Weekly downloads
2
-60%
Maintainers
1
Weekly downloads
 
Created
Source

Better Auth Nuxt

npm version npm downloads License Nuxt

A Nuxt module for simple, flexible authentication in your Nuxt applications.

Features

  • ⚙️  Auto-scanning of client and server configs for end-to-end TS support
  • 🚀  Built-in authentication middleware
  • 🔑  Multiple authentication strategies (username, email, ...)
  • 🛡️  Role-based access control
  • 🔄  Session management
  • 🔒  Redirect handling for authenticated/unauthenticated users

Quick Setup

  • Install the module:
# Using npm
npm install better-auth-nuxt better-auth

# Using yarn
yarn add better-auth-nuxt better-auth

# Using pnpm
pnpm add better-auth-nuxt better-auth
  • Add the module to your nuxt.config.ts:
export default defineNuxtConfig({
  modules: ['better-auth-nuxt'],

  betterAuth: {
    // Configure auth endpoints (default: '/api/auth/**')
    endpoint: '/api/auth/**',

    // Configure redirect paths
    redirectOptions: {
      redirectGuestTo: '/auth/login',
      redirectUserTo: '/',
      redirectUnauthorizedTo: '/401',
    },

    // Configure client and server options
    options: {
      client: {
        basePath: '/api/auth',
        // Optional: baseURL, disableDefaultFetchPlugins
      },
      server: {
        appName: 'My Nuxt App',
        // Optional: baseURL, basePath, secret
      },
    },
  }
})
  • Use the module in your pages:
<script setup>
// Protect route for authenticated users only
definePageMeta({
  auth: {
    only: 'user',
  }
})

// Access auth functionality
const { loggedIn, user, signOut } = useUserSession()
</script>

<template>
  <div v-if="loggedIn">
    <h1>Welcome, {{ user?.name }}</h1>
    <button @click="signOut()">Sign Out</button>
  </div>
</template>

Module Options

Auth Configuration

interface ModuleOptions {
  // Auth endpoint
  endpoint: string

  // Patterns to match auth configuration files
  serverConfigs?: string[]
  clientConfigs?: string[]

  // Client and server options
  options: {
    client?: ModuleClientOptions
    server?: ModuleServerOptions
  }

  // Redirect options
  redirectOptions: {
    redirectUserTo?: string
    redirectGuestTo?: string
    redirectUnauthorizedTo?: string
  }
}

Server Options

interface ModuleServerOptions {
  appName?: string   // Application name
  baseURL?: string   // Base URL for the auth API
  basePath?: string  // Base path for the auth API
  secret?: string    // Secret for JWT/session encryption
}

Client Options

interface ModuleClientOptions {
  baseURL?: string                  // Base URL for the auth API
  basePath?: string                 // Base path for the auth API
  disableDefaultFetchPlugins?: boolean // Disable default fetch plugins
}

API Reference

Client-side Composables

useUserSession()

Provides access to the authenticated user session and auth methods.

const {
  // State
  loggedIn,         // Ref<boolean> - Is the user logged in
  user,             // Ref<User> - Current user data
  session,          // Ref<Session> - Current session data

  // Methods
  fetchSession,     // () => Promise<void> - Fetch current session
  signIn: {
    username,       // (credentials) => Promise<void> - Sign in with username
    email,          // (credentials) => Promise<void> - Sign in with email
  },
  signUp: {
    username,       // (userData) => Promise<void> - Register with username
    email,          // (userData) => Promise<void> - Register with email
  },
  signOut,          // (options?) => Promise<void> - Sign out the user

  // Configuration
  options,          // Auth configuration options
} = useUserSession()

Server-side Utilities

useAuth()

Access the auth instance on the server.

// In API route handlers:
const auth = useAuth()

Route Protection

Use the auth meta property to protect routes:

definePageMeta({
  auth: {
    // Only allow specific roles
    only: 'user' | 'admin' | 'guest' | ['user', 'admin'],

    // Custom redirect paths (override global config)
    redirectUserTo: '/dashboard',
    redirectGuestTo: '/login',
    redirectUnauthorizedTo: '/unauthorized',
  }
})

Configuration Files

You can create configuration files to customize authentication:

Server Configuration

Create a *.better-auth.ts file to configure server-side auth:

// server/my-auth.better-auth.ts
import type { BetterAuthOptions } from 'better-auth'

export default () => ({
  // Custom server-side auth configuration
} satisfies BetterAuthOptions)

Client Configuration

Create a *.better-auth-client.ts file to configure client-side auth:

// app/my-auth.better-auth-client.ts
import type { ClientOptions } from 'better-auth'

export default {
  // Custom client-side auth configuration
} satisfies ClientOptions

Note: After adding or modifying configuration files, run pnpm nuxt prepare to ensure your changes are properly recognized by Nuxt.

Contribution

Local development
# Install dependencies
pnpm install

# Generate type stubs
pnpm dev:prepare

# Develop with the playground
pnpm dev

# Build the playground
pnpm dev:build

# Run ESLint
pnpm lint

# Run Vitest
pnpm test
pnpm test:watch

# Release new version
pnpm release

FAQs

Package last updated on 16 May 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts