Cloud

Audit Logging

Immutable, event-driven audit trail for compliance and security.

2 min readDocumentationEdit this page

Overview

The audit system emits structured, immutable events onto the AxilJS global event bus. It captures who did what, when, where, and whether it succeeded — providing the foundation for SOC2, HIPAA, and GDPR compliance.

Automatic Request Auditing

Attach the middleware globally to log every HTTP request automatically.

typescript
import { auditMiddleware } from '@axiljs/cloud'
 
app.use(auditMiddleware())

Each request generates an event containing:

  • Action — HTTP method and path (e.g. POST /api/users)
  • Actor — Authenticated user ID or anonymous
  • Tenant — Resolved tenant ID from multi-tenancy middleware
  • Request ID — Correlation ID from the request lifecycle
  • Status — HTTP status code and success/failure flag
  • Duration — Response time in milliseconds
  • Client — IP address and user agent

Manual Audit Events

Log business-level actions that don't correspond to HTTP requests.

typescript
import { auditLog } from '@axiljs/cloud'
 
auditLog({
  action: 'user.password_reset',
  actor: { id: adminId, type: 'user' },
  tenantId: tenant.id,
  target: { type: 'user', id: targetUserId },
  metadata: { reason: 'support_request', ticketId: 'TK-4421' },
  ip: req.ip,
  userAgent: req.headers['user-agent'],
  success: true,
})

Persisting Audit Events

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

typescript
import { getGlobalEventBus } from '@axiljs/events'
 
// PostgreSQL
getGlobalEventBus().on('audit.log', async (event) => {
  await db.auditLog.insert(event)
})
 
// S3 / WORM storage
getGlobalEventBus().on('audit.log', async (event) => {
  await s3.putObject({
    Bucket: 'audit-trail',
    Key: `${event.timestamp}/${event.id}.json`,
    Body: JSON.stringify(event),
  })
})

Architecture

The audit middleware uses Node.js finish and close response lifecycle events rather than monkey-patching res.raw.end. This 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
app.use(auditMiddleware({
  logToConsole: false, // Disable coloured console output in production
}))

Event Schema

typescript
interface AuditEvent {
  action:     string
  actor:      { id: string | number; type: 'user' | 'system' | 'api' | 'service' }
  tenantId?:  string
  target?:    { type: string; id: string | number }
  metadata:   Record<string, unknown>
  ip?:        string
  userAgent?: string
  requestId?: string
  success:    boolean
  error?:     string
  timestamp:  string  // ISO 8601
}

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY