X Enterprises
fastify-xauth-better

auditLog.log(event, data)

Writes a structured audit event to the AuthAuditLog Prisma model.

auditLog.log(event, data)

Writes a structured audit event to the AuthAuditLog table. Event name must be one of the 14 allowed event strings. IP address and user agent are automatically extracted from the request when provided.

Signature

instance.auditLog.log(
  event: string,
  data?: {
    userId?: string
    targetId?: string
    metadata?: Record<string, unknown>
    request?: FastifyRequest
  }
): Promise<AuthAuditLog>

Params

NameTypeRequiredDescription
eventstringYesOne of the 14 allowed audit event names (see table below)
data.userIdstringNoID of the user performing the action
data.targetIdstringNoID of the affected resource or user
data.metadataobjectNoArbitrary JSON — stored as Json in Prisma
data.requestFastifyRequestNoFastify request — used to capture IP and user-agent automatically

Allowed events

CategoryEvent
Loginauth.login.success, auth.login.failed, auth.logout
Passwordauth.password.changed, auth.password.reset.requested, auth.password.reset.completed
2FAauth.2fa.enabled, auth.2fa.disabled
Sessionauth.session.revoked
Accountauth.account.linked, auth.account.banned
Organizationauth.org.joined, auth.org.left, auth.org.role.changed

Returns

Promise<AuthAuditLog> — the created Prisma record.

Throws

  • Error: Invalid audit event: {event} — the event string is not in the allowed list

Examples

Log a successful login

const userAuth = fastify.xauthbetter.get("user");

fastify.post("/api/login-webhook", async (request) => {
  const { userId } = request.body;

  await userAuth.auditLog.log("auth.login.success", {
    userId,
    metadata: { method: "oauth", provider: "google" },
    request,
  });

  return { ok: true };
});

Log an org role change with target user

await userAuth.auditLog.log("auth.org.role.changed", {
  userId: request.user.id,          // who made the change
  targetId: memberId,               // who was changed
  metadata: {
    orgId: request.organization.id,
    previousRole: "member",
    newRole: "admin",
  },
  request,
});

See also

AI Context

package: "@xenterprises/fastify-xauth-better"
method: fastify.xauthbetter.get(name).auditLog.log(event, data)
use-when: Write a structured audit event to the AuthAuditLog table
events: sign_in, sign_out, sign_up, password_reset, email_verification, org_created, org_updated, org_deleted, member_added, member_removed, role_changed, 2fa_enabled, 2fa_disabled, impersonation_started
Copyright © 2026