---
title: "Record and review activity"
description: "The activity trail: what the package records, who reads which part of it, events of your own with recordBackendEvent, onEvent, a year of retention and erasure."
canonical_url: "https://nuxt-backend.dev/docs/build/auth/admin/audit-log"
---
# Record and review activity

> The activity trail: what the package records, who reads which part of it, events of your own with recordBackendEvent, onEvent, a year of retention and erasure.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/security)
- [API reference](https://nuxt-backend.dev/docs/reference/api/audit)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/audit.ts)

Everything that happens to an account, and inside a workspace, lands on one **activity trail**: sign-ins and sign-outs, passkeys, email changes, devices signed out, workspace invitations, memberships and roles, and an administrator's role changes and impersonations. The package records each event where it happens, as one row that holds ids and never an address or a name, and keeps it for a year. People read their own activity on `/security`, a workspace's owners and admins read the workspace's on `/settings`, and administrators read everything. Events of your own go on the same trail.

Better Auth keeps no history of its own, so the trail is the package's. It lives in the `backend` component, beside your data, and the `auth` capability writes to it from Better Auth's hooks.

## How it works

- **One event path.** The `auth` capability records its events itself (the [Events](https://nuxt-backend.dev/docs/reference/backend/events#backend-events) reference lists each kind and what records it). Your code records through `recordBackendEvent`. Both write through the `backend` component, so a row looks the same whoever wrote it.
- **One row per event.** A row names who acted (`actorId`), the administrator behind an impersonated session (`impersonatorId`), the account it is about (`subjectId`), the workspace it happened in (`entityId`), the thing acted on (`targetId`, such as a passkey's or an invitation's id), and the kind's own `data` (a role, a sign-in method).
- **One log line.** Each event writes `audit.recorded` to the deployment's logs, with its type and its id and nothing else.
- **It never fails what it records.** When an event of the `auth` capability cannot be recorded, the sign-in, the invitation or the role change goes through, and the logs say `audit.record_failed`.
- **What it derives.** Each kind declares the channels it may notify on beside its row: in the app, by email, or neither. A billing, gift or referral kind never derives an email, because the billing provider emails its own customers. The [`notifications` capability](https://nuxt-backend.dev/docs/build/email/notifications) delivers them: the in-app ones in the same transaction that records the event.

The scaffold wires it in `backend/audit.ts`, and passes it to `setupAuth` so the `auth` capability's events reach your `onEvent` too:

```ts [backend/audit.ts]
import { setupAudit } from 'nuxt-backend/audit'
import { components } from './_generated/api'

export const audit = setupAudit(components)

// The reads behind useAuditLog and <AuditLog>.
export const { listActivity, listWorkspaceActivity, listAllActivity } = audit.api
```

```ts [backend/auth.ts]
import { audit } from './audit'

export const { createAuth /* , … */ } = setupAuth(components, query, {
  email,
  rateLimiter,
  audit,
})
```

An app that leaves `audit` out of `setupAuth` still records every auth event, through the component; only `onEvent` never hears of them. The `setUserRole` bootstrap records a role it changes the same way, as the app's (`admin.role_changed` with no one signed in), and setting the role an account already holds records nothing.

## Read it

`<AuditLog>` lists a page of events at a time, newest first, each as one sentence with who acted first, then what the sentence leaves out: the account it is about, the workspace, the sign-in method, an administrator acting for the account. `scope` picks whose activity:

<table>
<thead>
  <tr>
    <th>
      <code>
        scope
      </code>
    </th>
    
    <th>
      Lists
    </th>
    
    <th>
      Read by
    </th>
    
    <th>
      Query
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        mine
      </code>
      
       (default)
    </td>
    
    <td>
      what happened to the signed-in account
    </td>
    
    <td>
      the account itself
    </td>
    
    <td>
      <code>
        listActivity
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        workspace
      </code>
    </td>
    
    <td>
      everything in the active workspace
    </td>
    
    <td>
      its owners and admins (<code>
        workspaceRoles
      </code>
      
      )
    </td>
    
    <td>
      <code>
        listWorkspaceActivity
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        all
      </code>
    </td>
    
    <td>
      every event
    </td>
    
    <td>
      administrators (<code>
        adminRoles
      </code>
      
      )
    </td>
    
    <td>
      <code>
        listAllActivity
      </code>
    </td>
  </tr>
</tbody>
</table>

```vue
<template>
  <AuditLog scope="workspace" :limit="10" />
</template>
```

`/security` renders the account's own activity under its other sections, and `/settings` the workspace's for its owners and admins. A read answers `null` to anyone it is not for: signed out, a member who manages nothing, or a removed member. The component renders nothing then (and `useAuditLog` sets `isRefused`), so a page can mount it for everyone; signed out, it shows its empty state.

In an account's own activity, an administrator who acted on it is unnamed ("An administrator began acting as you", "An administrator signed a session out"); administrators read each other's names. A workspace's activity names its members, past ones included, and an erased account reads as "A deleted account".

`useAuditLog({ scope, limit })` is the same list for a page of your own: `events` (the page in view), `next()` and `previous()` to page by cursor, `hasMore`, `hasPrevious`, `isLoading` and `error`. The first page is live, so an event recorded while it is in view appears at its top; older pages hold still.

```ts
const activity = useAuditLog({ scope: 'mine', limit: 20 })
await activity.next()
```

Each entry carries `type`, `at`, `actor` and `subject` (each `{ kind, id, name }`, `kind` one of `you`, `user`, `administrator`, `app` and `erased`), `workspace`, `impersonated`, `targetId` and `data`. The `audit` label group words each kind as `events.<area>.<kind>`: override a sentence in `appConfig.backend.labels.audit`, or give a kind of your own one (`events.app.strip_archived`), which otherwise reads as `other`.

## Record your own events

Record an event of your own from a mutation or an action. Its type lives under `app.`:

```ts [backend/strips.ts]
import { v } from 'convex/values'
import { audit } from './audit'
import { workspace } from './functions'

export const archive = workspace.mutation({
  args: { stripId: v.id('strips') },
  handler: async (ctx, { stripId }) => {
    await ctx.db.patch('strips', stripId, { archived: true })
    await audit.recordBackendEvent(ctx, {
      type: 'app.strip_archived',
      entityId: ctx.workspace.id,
      targetId: stripId,
    })
  },
})
```

- **Who acted** is the caller's identity unless you say otherwise: the account, and the administrator visiting it, from the token's claims. Pass `actor: { userId }` from code no one signed in to (a webhook, a job), or `actor: null` for the app itself.
- **Who it is about** (`subjectId`) is the actor unless you say otherwise; `null` names no one. The account it is about reads the event in its own activity.
- **Where** (`entityId`) puts it in a workspace's activity.
- **What** (`data`) holds at most 16 flat values: strings, numbers, booleans and lists of at most 32 strings, each string 128 characters at most. Keep personal data out of it: a row is kept for a year.
- **In a mutation** the row commits or rolls back with the mutation's own writes, so an archive that fails records nothing.

A type the catalog does not know and that is not under `app.`, a field a package kind does not carry, or a workspace kind without its workspace is refused as [`invalid_input`](https://nuxt-backend.dev/docs/reference/backend/errors#invalid_input), the field named. A package kind takes its own fields, typed: `audit.recordBackendEvent(ctx, { type: 'workspace.member_invited', entityId, data: { role: 'member' } })`.

## Hear of every event

`onEvent` is an internal action of yours that hears of every event once it is recorded, the package's own and yours: forward one to a chat channel, an analytics pipeline or a SIEM. It takes `{ event: vBackendEvent }`, and you pass it by its reference:

```ts [backend/audit.ts]
import { setupAudit, vBackendEvent } from 'nuxt-backend/audit'
import { components, internal } from './_generated/api'
import { internalAction } from './_generated/server'

export const audit = setupAudit(components, { onEvent: internal.audit.onEvent })

export const onEvent = internalAction({
  args: { event: vBackendEvent },
  handler: async (ctx, { event }) => {
    if (event.type === 'admin.impersonation_started') {
      // Tell the support channel, keyed on event.id.
    }
  },
})
```

The transaction that recorded the event schedules it, so it runs once that transaction commits, in an action of its own. It is fire and forget: nothing retries a run that fails, and the event stays recorded. [Hooks and guarantees](https://nuxt-backend.dev/docs/reference/backend/hooks#setupaudit-onevent) has the whole promise.

## How long a row is kept

The backend component's hourly maintenance deletes a row 365 days after it was recorded (`AUDIT_EVENT_RETENTION_MS`, on [Limits and retention](https://nuxt-backend.dev/docs/reference/backend/limits)). Nothing in your app schedules it.

## Erasure

When an account is deleted (the person's own deletion, or an administrator's removal), its part of the trail goes with it, by one rule:

- **Kept, pseudonymized:** every row an administrator took part in, acting on the account (a role set, a visit, a device signed out) or acting as it in an impersonated session. It is the record of what an administrator did, and no account's deletion removes it, the administrator's own included.
- **Removed:** the account's own record. That is its sign-ins, passkeys, email and session changes and every row in its personal workspace, which is named after the person.
- **Kept, pseudonymized:** the rest of the rows that belong to someone else's record too: a workspace's trail (the workspace's other managers read it) and every row where the account acted on someone else, or someone else on it.

The account's id becomes one pseudonym, the same in every row it touches, so the trail still reads "A deleted account invited… then removed…". The pseudonym itself is random, but a row still carries what it was about: a workspace keeps its name until the workspace itself is renamed or deleted.

An account's [erasure](https://nuxt-backend.dev/docs/build/auth/accounts/data#what-an-erasure-removes) runs it, as one of its participants, when the account is deleted. `audit.forgetSubject(ctx, userId)` runs it for an id of your own choosing, batched for a long trail. An app kind's `data` is yours to keep personal data out of.

The [feature flags](https://nuxt-backend.dev/docs/ship/operate/flags) are another participant: the account's id leaves every flag's account targets. A participant that keeps failing logs `account.erasure_failed`. A `flag.changed` row never named whom a flag targets.

## In tests

The test app (`defineBackendTestApp` from `nuxt-backend/test`) mounts the component with its audit module, so a mutation that records an event writes its row as it does on a deployment. Read it back through your `listActivity` as the caller (`asUser`).

## Related

- [Events](https://nuxt-backend.dev/docs/reference/backend/events#backend-events): every kind, who reads it, what it carries and what records it.
- [Manage passkeys and sessions](https://nuxt-backend.dev/docs/build/auth/accounts/security): the `/security` page the account's activity sits on.
- [Require a recent sign-in](https://nuxt-backend.dev/docs/build/auth/access/step-up): the writes that ask before they run.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
