{"id":16710,"library":"better-auth-audit-logs","title":"Better Auth Audit Logs Plugin","description":"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.","status":"active","version":"0.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/ejirocodes/better-auth-audit-logs","tags":["javascript","better-auth","better-auth-plugin","audit-log","audit-trail","auth","authentication","security","logging","typescript"],"install":[{"cmd":"npm install better-auth-audit-logs","lang":"bash","label":"npm"},{"cmd":"yarn add better-auth-audit-logs","lang":"bash","label":"yarn"},{"cmd":"pnpm add better-auth-audit-logs","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core authentication library this package extends.","package":"better-auth","optional":false},{"reason":"Schema validation for audit log entries.","package":"zod","optional":false},{"reason":"Type definitions are heavily utilized and `typescript >= 5` is required.","package":"typescript","optional":false}],"imports":[{"note":"This is the primary server-side plugin factory for integrating with `better-auth`.","wrong":"const { auditLog } = require('better-auth-audit-logs');","symbol":"auditLog","correct":"import { auditLog } from 'better-auth-audit-logs';"},{"note":"The client-side plugin has a distinct import path to avoid bundling server-side code in browser environments.","wrong":"import { auditLogClient } from 'better-auth-audit-logs';","symbol":"auditLogClient","correct":"import { auditLogClient } from 'better-auth-audit-logs/client';"},{"note":"Type import for the audit log entry structure. Available for both server and client contexts.","symbol":"AuditLogSchema","correct":"import type { AuditLogSchema } from 'better-auth-audit-logs';"}],"quickstart":{"code":"import { betterAuth } from 'better-auth';\nimport { auditLog } from 'better-auth-audit-logs';\n\n// Initialize Better Auth with the audit log plugin\nexport const auth = betterAuth({\n  plugins: [auditLog()],\n  // Assuming other Better Auth configurations here, e.g., adapters\n  // adapter: someAdapter(...),\n});\n\n// In a separate script or CLI for database migrations:\n// Make sure to have `@better-auth/cli` installed.\n// Run `npx @better-auth/cli generate`\n// This command will generate database migrations for the `auditLog` table.\n// Subsequently, run your database migration command (e.g., `npx prisma migrate dev` for Prisma).\n\n// Example of client-side usage (e.g., in a React component or API handler)\nimport { createAuthClient } from 'better-auth/client';\nimport { auditLogClient } from 'better-auth-audit-logs/client';\n\nconst authClient = createAuthClient({\n  plugins: [auditLogClient()],\n});\n\nasync function fetchAuditLogs() {\n  try {\n    const { data } = await authClient.auditLog.listAuditLogs({\n      query: { status: 'failed', limit: 5, action: 'sign-in:email' },\n    });\n    console.log('Recent failed sign-ins:', data);\n\n    await authClient.auditLog.insertAuditLog({\n      action: 'admin:user-delete',\n      status: 'success',\n      severity: 'high',\n      metadata: { deletedUserId: 'user-xyz', adminId: 'admin-abc' },\n    });\n    console.log('Manually logged an admin action.');\n\n  } catch (error) {\n    console.error('Error fetching or inserting audit logs:', error);\n  }\n}\n\n// Call the function, typically triggered by a user action or on mount\n// fetchAuditLogs();","lang":"typescript","description":"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."},"warnings":[{"fix":"If you are using a non-Prisma adapter and have an existing `audit_log` table, explicitly set `schema.auditLog.modelName: \"audit_log\"` in your plugin configuration to maintain compatibility.","message":"The default `modelName` for the audit log table changed from `audit_log` to `auditLog` to improve compatibility with Prisma adapters.","severity":"breaking","affected_versions":">=0.2.0"},{"fix":"Ensure your `better-auth` and `typescript` peer dependencies are up-to-date by running `npm install better-auth@latest typescript@^5`.","message":"Requires `better-auth >= 1.0.0` and `typescript >= 5`. Older versions of `better-auth` are not compatible and will likely lead to runtime errors due to API mismatches.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"After installing the plugin, execute `npx @better-auth/cli generate` and then apply the generated migrations using your ORM's migration tool (e.g., `npx prisma migrate dev`).","message":"The audit log plugin adds an `auditLog` table to your database. You must run `npx @better-auth/cli generate` after installing to create the necessary migrations for your database adapter.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Always use `import { auditLogClient } from 'better-auth-audit-logs/client';` for client-side functionality. Importing from the main package path will lead to bundling issues or runtime errors in browser environments.","message":"The client-side `auditLogClient` plugin must be imported from `better-auth-audit-logs/client`.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `better-auth-audit-logs` is installed and the client plugin is imported as `import { auditLogClient } from 'better-auth-audit-logs/client';`.","cause":"Incorrect import path for the client-side plugin, or missing package installation.","error":"Error: Cannot find module 'better-auth-audit-logs/client'"},{"fix":"Run `npx @better-auth/cli generate` to create the migration files, then apply them using your ORM's migration command (e.g., `npx prisma migrate dev`).","cause":"Database migrations for the audit log schema have not been generated or applied.","error":"Error: 'auditLog' table not found or column missing in database."},{"fix":"Ensure `auditLogClient()` is included in the `plugins` array when calling `createAuthClient({ plugins: [auditLogClient()] })`.","cause":"The `auditLogClient()` plugin was not correctly registered with `createAuthClient`.","error":"TypeError: Cannot read properties of undefined (reading 'auditLog') on authClient"},{"fix":"Review the `insertAuditLog` call and ensure all required fields are present and conform to the expected schema (e.g., `action: 'some-action'`, `status: 'success'`, `severity: 'low'`).","cause":"When manually inserting an audit log, a required field (like `action`, `status`, `severity`) was omitted or provided with an incorrect type.","error":"ZodError: Validation failed: Expected string, received undefined at 'action'"}],"ecosystem":"npm"}