Cloud

Audit Logging

Event-driven audit trail for compliance and security, emitted on the AxilJS global event bus per request or per business action.

3 min readUpdated DocumentationEdit this page
On this page7

Overview

The audit system emits structured events onto the AxilJS global event bus (@axiljs/events) under the name 'audit.log'. It captures who did what, when, where, and whether it succeeded. Persisting the events is up to your subscribers, which makes it a foundation for SOC2, HIPAA, and GDPR workflows.

Automatic Request Auditing

Attach the middleware globally to audit every HTTP request.

TypeScript
TS
import { auditMiddleware } from '@axiljs/cloud'

app.use(auditMiddleware())

Each request generates one event when the response finishes (or the client disconnects), containing:

  • Action: method and path, for example POST /api/users
  • Actor: req.locals.user as { id, type: user.type ?? 'user' }, or { id: 'anonymous', type: 'api' }
  • Tenant: req.locals.tenant.id from multiTenancy()
  • Request ID: req.locals.requestId from correlationId()
  • Result: success is true for status 200–399; otherwise error is 'HTTP <status>'
  • Metadata: method, path, durationMs, statusCode
  • Client: req.ip and the user-agent header

Manual Audit Events

Log business-level actions that don't correspond to HTTP requests. timestamp is added for you.

TypeScript
TS
1import { auditLog } from '@axiljs/cloud'
2
3auditLog({
4  action: 'user.password_reset',
5  actor: { id: adminId, type: 'user' },
6  tenantId: tenant.id,
7  target: { type: 'user', id: targetUserId },
8  metadata: { reason: 'support_request', ticketId: 'TK-4421' },
9  ip: req.ip,
10  userAgent: req.headers['user-agent'],
11  success: true,
12})
13
14// Second argument: { logToConsole?: boolean } (default true)
15auditLog({ action: 'cron.cleanup', actor: { id: 'scheduler', type: 'system' }, metadata: {}, success: true },
16  { logToConsole: false })

Persisting Audit Events

Subscribe to the global event bus to store events in your preferred backend.

TypeScript
TS
1import { getGlobalEventBus } from '@axiljs/events'
2
3// PostgreSQL
4getGlobalEventBus().on('audit.log', async (event) => {
5  await db.auditLog.insert(event)
6})
7
8// S3 / WORM storage (events have no id field; derive a key)
9getGlobalEventBus().on('audit.log', async (event) => {
10  await s3.putObject({
11    Bucket: 'audit-trail',
12    Key: `${event.timestamp}/${event.requestId ?? crypto.randomUUID()}.json`,
13    Body: JSON.stringify(event),
14  })
15})

Architecture

The audit middleware listens for the finish and close events on the underlying Node response (res.raw) instead of monkey-patching res.raw.end. A guard flag ensures:

  • Safe operation with streaming responses
  • No interference with other middleware
  • Exactly-once event emission per request
  • Compatibility with all AxilJS response methods

Options

TypeScript
TS
app.use(auditMiddleware({
  logToConsole: false, // default true: one coloured [AUDIT] line per event
}))
OptionTypeDefaultDescription
logToConsolebooleantruePrint a line to stdout for each audit event

Event Schema

TypeScript
TS
1interface AuditEvent {
2  action:     string
3  actor:      { id: string | number; type: 'user' | 'system' | 'api' | 'service' }
4  tenantId?:  string
5  target?:    { type: string; id: string | number }
6  metadata:   Record<string, unknown>
7  ip?:        string
8  userAgent?: string
9  requestId?: string
10  success:    boolean
11  error?:     string
12  timestamp:  string  // ISO 8601
13}

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY