Skip to main content
An organization owner or admin wants to know who did what. They search both ways: by person (“what did this warehouse worker do?”) and by thing (“who accepted delivery 123, and what changed?”). The audit-logs module stores each event as a row with the organization, actor, action, entity, before and after state, channel and a service-mode flag. It gives you an /audit-log page with filters and an <AuditTrail> component that shows the history of a single entity. Events are recorded by the code that changes data: the core (membership, superadmin entering an organization), other kit modules (api-keys, uploads) and your own features. They all call the same core function, trackAudit, and the module plugs a database writer in behind it. Actions are open-ended: action is any string, and the module that records an action declares its label.

What it doesn’t do

  • No retention. Nothing deletes old entries, so the table grows without limit. Entries only disappear together with their organization. A planned background jobs module will cover retention and cleanup.
  • No automatic recording. A change that your code doesn’t pass to trackAudit, and that the module’s better-auth plugin doesn’t catch, never reaches the log. Calling trackAudit after every data change is a convention; nothing enforces it.
  • No reads, sign-ins or account changes. Password, email, global role, ban and impersonation events aren’t logged. The plugin catches five organization endpoints only.
  • No export and no cross-organization view. Every query is limited to the active organization.
Skip the module if nobody will read the log. Your code can call trackAudit and declare auditActions without it, so you can add the module later without changing that code. Events from before the module was added are not stored anywhere.

Requirements

Install and remove

1

Add the module

This copies the module files, adds auditLogs AuditLog[] to User and Organization in the wa:relations region, runs gato generate and npm install.
2

Create the migration

Commit the migration. If you used --no-install, also run npm run db:generate: Prisma 7’s migrate dev doesn’t run the generator, and without it prisma.auditLog doesn’t exist.
No variables, services or CI changes are needed.
On deployment, npx prisma migrate deploy applies the migration. Events are recorded from the first request served by the new version; earlier events can’t be reconstructed.

Removing the module

npx gato remove audit-logs refuses when a project module lists audit-logs in requires, for example because it renders <AuditTrail>. After a successful removal:

What the module adds

Module definition

src/features/audit-logs/module.ts:

The AuditLog model

prisma/schema/audit-logs.prisma, table audit_logs: Indexes: (organizationId, createdAt), (organizationId, entityType, entityId) and (organizationId, userId, createdAt). Each starts with organizationId, because every query filters by organization. Deleting an organization deletes its entries (onDelete: Cascade). Deleting a user keeps the entries with userId set to null, shown as “System”. Writing an event with an organizationId that doesn’t exist fails on the foreign key inside the sink; trackAudit catches and logs it.

The /audit-log page

The page calls requireModuleAccess("audit-logs"), parses URL parameters and loads entries and the list of actors in parallel. Filters, sorting and paging live in the URL, so you can share a link to a filtered view. Invalid URL parameters don’t cause errors: each bad value falls back to its default or is ignored.
Date filters use the time zone of the Node process (TZ), not UTC or the browser’s zone. The date column shows the browser’s local time. On a UTC server, a user in another zone sees entries near midnight shifted relative to the filter boundaries.

Access by role

The page, its queries and <AuditTrail> are available to owners and admins of the active organization and to accounts with the global admin or superadmin role. A member gets a 404 on the page, and <AuditTrail> renders nothing for them. Owners and admins see every entry of their organization, including superadmin service-mode entries and the contents of oldData and newData, such as invited email addresses. See Auth and roles. The module has no server actions ("use server" files), so no one can add or change an entry from the browser.

Events recorded by the core and kit modules

The module’s better-auth plugin (src/features/audit-logs/auth.ts) catches five organization endpoints. It takes the organization from the endpoint response, not the request body, and a failed endpoint call creates no entry. Other events are recorded by core and module code directly. No kit code writes the API channel or a credentialId. Your API routes fill those in; see Recording from an API key route.

Entry point contracts

trackAudit, auditActor and AuditSink live in the core (src/shared/lib/audit.ts), and auditActions is a defineModule field. They exist in every project, with or without the module.

trackAudit

src/shared/lib/audit.ts
  • Input. organizationId, actorUserId, action and entityType are required. Take the organization from the context (auditActor(context)), never from user input.
  • When to call. After a successful write, before returning the result.
  • What it does. Calls each sink in auditSinks in order with the same event object and awaits each one.
  • Errors. A failing sink is logged as trackAudit failed and the next sink still runs. trackAudit never throws, so a failed audit write doesn’t fail the command or roll back its change. The user sees success; only the logs show the missing entry.
  • No transaction. The entry is written in a separate query, outside your command’s transaction.
  • Without the module. If no feature has an audit-sink.ts, the call records nothing, logs nothing and returns normally.
  • Security. audit.ts has no "use server" directive, so the browser can’t call trackAudit. Don’t export a server action that accepts an event from the client and forwards it.

auditActor

auditActor(context) takes an OrgContext and returns { organizationId, actorUserId, serviceMode }. Spread it into the event (...auditActor(context)) and a superadmin’s change in service mode gets serviceMode: true and a “Service mode” badge. An event built by hand without serviceMode is stored with false, even in service mode. getOrgContext() and requireModuleAccess() return the context. Routes authenticated with an API key have no session and no OrgContext, so they build the event by hand.

AuditSink

A sink is a function (event: AuditEvent) => Promise<void> exported as auditSink from src/features/<name>/audit-sink.ts. gato generate adds it to auditSinks, after kit module sinks. The module’s sink is a one-liner:
src/features/audit-logs/audit-sink.ts
You can add your own sink, for example to forward events to an external system.
A sink receives the event before redaction. Only writeAuditLog redacts. A sink that stores or sends oldData and newData must redact them itself, for example with redactSensitive from the module. Don’t mutate the event: every sink gets the same object. A slow sink delays every command that calls trackAudit, because sinks run one after another.

auditActions

The auditActions?: { action: string; labelKey: string }[] field in defineModule tells the log how to display an action. The label is labelKey in the translation namespace of the declaring module, which is its feature folder name, so key must equal the folder name.
  • Who reads it. The /audit-log page (table labels and the action filter) and <AuditTrail>.
  • No declaration. The action shows as a raw string and isn’t in the filter list. Recording still works: the declaration isn’t validation.
  • Missing translation key. next-intl reports MISSING_MESSAGE and shows the key path.
  • Same action in two modules. The first in the registry wins: core, then kit modules, then project modules.

Redaction

Owners and admins read the log, so before writing, redactSensitive replaces the value of every sensitive key with "[REDACTED]" at any depth in objects and arrays. A key is sensitive when, lowercased and with - and _ removed, it contains password, secret, token, apikey, authorization, cookie, privatekey or hashedkey. That covers newPassword, client_secret, X-API-Key, set-cookie and tokens. Objects with toJSON are redacted after serialization; Date values and primitives pass through.
Redaction works on key names only. A secret under a neutral name (value, code, pin) or inside a string ("Bearer abc" in a header field) is stored and shown to owners and admins. Personal data such as email addresses is not redacted. Pass only the fields you want in the log, never a whole database row.

Record an event from your code

The examples below come from a deliveries project module that records accepted deliveries.

In a command

Call trackAudit after the service-mode check and after the write:
src/features/deliveries/services/commands/receive-delivery-command.ts
The order matters. A refused service-mode confirmation, invalid input or a failed write never reaches trackAudit, so no entry is written. newData contains only the fields you want in the log. A failed audit write doesn’t change the command result.

Add an action label

Declare the label in the module that records the action:
src/features/deliveries/module.ts
Add action-delivery-accepted to src/features/deliveries/i18n/en.json and every other locale file. A new module.ts or translation file needs npx gato generate; a new entry in an existing auditActions array doesn’t.

Show an entity’s history

<AuditTrail entityType entityId /> is an async server component. Render it in a page or another server component, not in a "use client" component:
src/app/[locale]/(app)/deliveries/page.tsx
  • It shows the 50 newest entries for the entity in the active organization, newest first: time, action label and actor (“System” when there is none). With no entries it shows “No history”.
  • A user without module access (role member) sees nothing: the component returns null and the page still renders, so you can place it on pages every role can open.
  • Entries with the same entityId in another organization, or with another entityType, are not shown.
  • Time is formatted on the server (yyyy-MM-dd HH:mm) in the server’s time zone.
  • Each component runs its own query, so a list of 20 entities runs 20 queries.
Importing <AuditTrail> ties your feature to the module. Add "requires": ["audit-logs"] to the feature’s projectModules entry in .wa/kit.json, so gato remove audit-logs refuses instead of breaking your build.

Recording from an API key route

A route authenticated with an API key has no session, so there is no auditActor. Build the event from the key context: organizationId from the context, actorUserId: null, channel: "API" and credentialId set to the key ID. The log then shows an “API” badge and “System” as the actor. See API keys for a full example.

Code that works without the module

A feature that should run in projects with and without audit-logs:
  • calls trackAudit and auditActor from @/shared/lib/audit and declares auditActions. That works everywhere, and events start being stored after gato add audit-logs with no code change;
  • imports nothing from @/features/audit-logs/ (<AuditTrail>, redactSensitive, queries);
  • doesn’t list audit-logs in requires.
The core does the same: its commands call trackAudit without checking whether the module is installed.

Security and isolation

  • Isolation. Every module query filters by organizationId from the context: the entry list, the actor list and entity history. Filtering by a user ID from another organization returns nothing. An event is stored in event.organizationId, so take it from the context.
  • Owners and admins only, checked in the page, in each query and in <AuditTrail>. A member can’t read the queries even from another page, because the guard is in the query.
  • No writes from the browser. The module has no server actions and audit.ts has no "use server".
  • Redaction is name-based and misses secrets under neutral names and personal data.
  • Custom sinks get unredacted data.
  • A failed audit write doesn’t stop the command. Monitor your logs for trackAudit failed. See Logging and observability.
  • Service mode is visible only when the event gets serviceMode from auditActor(context).
  • No retention. Personal data in oldData and newData stays until the organization is deleted.

Testing

Integration test with the real sink. The strongest test for a command that calls trackAudit runs against a real database with the real trackAudit and the audit-logs sink, and checks the row in audit_logs. Mock only framework I/O (next/headers, next/cache, next/navigation, @/i18n/routing, next-intl/server) and the session with vi.spyOn(auth.api, "getSession").
src/features/deliveries/services/__tests__/receive-delivery-command.integration.test.ts
Add cases for invalid input (no row), a superadmin in service mode without confirmation (error, no row) and with confirmation (serviceMode: true). Use literal expected values, not values computed by production code. resetDatabase() truncates core tables with CASCADE, so audit entries go with their organizations. See Testing. Mocking trackAudit. When a test doesn’t need the row, replace only trackAudit and keep auditActor:
This checks the event contents, not redaction or storage. Don’t mock trackAudit in a test that should prove the entry lands in the right organization. Without the module. With no sink, a test using the real trackAudit passes but stores nothing, and the test database has no audit_logs table. Check event contents with a mock.

Troubleshooting

Reference

AuditEvent fields

Actions declared by the kit

Core actions are declared by audit-logs, not by the core, so without the module nothing displays them.

/audit-log URL parameters

Files