Better Auth Audit Logs Plugin

0.3.0 · active · verified Wed Apr 22

This package, `better-auth-audit-logs`, provides a plug-in for the `better-auth` authentication library, designed to automatically capture and store authentication lifecycle events. It is currently at version 0.3.0 and appears to have a fairly active release cadence, with several minor versions released recently. Key features include automatic logging of auth events (like sign-in, sign-up, password changes) with associated metadata such as IP address and user agent, support for custom storage backends (Prisma, Drizzle, MongoDB examples are provided), and PII redaction capabilities. It differentiates itself by offering a zero-config setup for automatic event capture when integrated with `better-auth`, and exposing query endpoints for retrieving logs, including the ability to insert custom audit entries for non-auth related administrative actions. It relies on `better-auth` for its core functionality and `zod` for schema validation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate the audit log plugin into a `better-auth` server instance and how to use its client-side capabilities to list existing logs and manually insert custom audit events.

import { betterAuth } from 'better-auth';
import { auditLog } from 'better-auth-audit-logs';

// Initialize Better Auth with the audit log plugin
export const auth = betterAuth({
  plugins: [auditLog()],
  // Assuming other Better Auth configurations here, e.g., adapters
  // adapter: someAdapter(...),
});

// In a separate script or CLI for database migrations:
// Make sure to have `@better-auth/cli` installed.
// Run `npx @better-auth/cli generate`
// This command will generate database migrations for the `auditLog` table.
// Subsequently, run your database migration command (e.g., `npx prisma migrate dev` for Prisma).

// Example of client-side usage (e.g., in a React component or API handler)
import { createAuthClient } from 'better-auth/client';
import { auditLogClient } from 'better-auth-audit-logs/client';

const authClient = createAuthClient({
  plugins: [auditLogClient()],
});

async function fetchAuditLogs() {
  try {
    const { data } = await authClient.auditLog.listAuditLogs({
      query: { status: 'failed', limit: 5, action: 'sign-in:email' },
    });
    console.log('Recent failed sign-ins:', data);

    await authClient.auditLog.insertAuditLog({
      action: 'admin:user-delete',
      status: 'success',
      severity: 'high',
      metadata: { deletedUserId: 'user-xyz', adminId: 'admin-abc' },
    });
    console.log('Manually logged an admin action.');

  } catch (error) {
    console.error('Error fetching or inserting audit logs:', error);
  }
}

// Call the function, typically triggered by a user action or on mount
// fetchAuditLogs();

view raw JSON →