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. CallingtrackAuditafter 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.
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
- Existing project
- New project
1
Add the module
auditLogs AuditLog[] to User and Organization in the wa:relations region, runs gato generate and npm install.2
Create the migration
--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.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,actionandentityTypeare 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
auditSinksin order with the same event object and awaits each one. - Errors. A failing sink is logged as
trackAudit failedand the next sink still runs.trackAuditnever 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.tshas no"use server"directive, so the browser can’t calltrackAudit. 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
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-logpage (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_MESSAGEand 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.
Record an event from your code
The examples below come from adeliveries project module that records accepted deliveries.
In a command
CalltrackAudit after the service-mode check and after the write:
src/features/deliveries/services/commands/receive-delivery-command.ts
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
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 returnsnulland the page still renders, so you can place it on pages every role can open. - Entries with the same
entityIdin another organization, or with anotherentityType, 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.
<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 noauditActor. 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 withoutaudit-logs:
- calls
trackAuditandauditActorfrom@/shared/lib/auditand declaresauditActions. That works everywhere, and events start being stored aftergato add audit-logswith no code change; - imports nothing from
@/features/audit-logs/(<AuditTrail>,redactSensitive, queries); - doesn’t list
audit-logsinrequires.
trackAudit without checking whether the module is installed.
Security and isolation
- Isolation. Every module query filters by
organizationIdfrom 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 inevent.organizationId, so take it from the context. - Owners and admins only, checked in the page, in each query and in
<AuditTrail>. Amembercan’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.tshas 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
serviceModefromauditActor(context). - No retention. Personal data in
oldDataandnewDatastays until the organization is deleted.
Testing
Integration test with the real sink. The strongest test for a command that callstrackAudit 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
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:
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.