TypeScript

NestJS Audit Logging Guide

Integrate AuditKit into your NestJS application using decorators, interceptors, and the built-in module system for clean, maintainable audit logging.

Overview

NestJS is the most popular enterprise Node.js framework, known for its modular architecture and dependency injection. AuditKit provides a dedicated NestJS module that integrates naturally with the framework's patterns. Use the @AuditLog() decorator to mark controller methods for automatic logging, or inject the AuditKitService into any provider for programmatic control. The module supports async configuration for loading credentials from environment variables or secret managers.

Getting started

1

Install the SDK

Add the AuditKit NestJS module.

TypeScript
npm install @auditkit/nestjs @auditkit/node
2

Register the module

Import AuditKitModule in your root AppModule with async configuration.

TypeScript
import { AuditKitModule } from '@auditkit/nestjs';

@Module({
  imports: [
    AuditKitModule.forRootAsync({
      useFactory: (config: ConfigService) => ({
        apiKey: config.get('AUDITKIT_API_KEY'),
        tenantResolver: (req) => req.user?.organizationId,
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}
3

Use the decorator

Add @AuditLog() to controller methods for automatic event capture.

TypeScript
import { AuditLog } from '@auditkit/nestjs';

@Controller('users')
export class UsersController {
  @Post(':id/role')
  @AuditLog({
    action: 'user.role_changed',
    targetType: 'user',
    targetId: (req) => req.params.id,
  })
  async changeRole(
    @Param('id') id: string,
    @Body() dto: ChangeRoleDto,
  ) {
    return this.usersService.changeRole(id, dto.role);
  }
}
4

Inject the service directly

For more control, inject AuditKitService into any provider.

TypeScript
import { AuditKitService } from '@auditkit/nestjs';

@Injectable()
export class PaymentsService {
  constructor(private readonly auditkit: AuditKitService) {}

  async processRefund(userId: string, paymentId: string) {
    const result = await this.stripe.refund(paymentId);

    await this.auditkit.log({
      action: 'payment.refunded',
      actor: { id: userId },
      target: { type: 'payment', id: paymentId },
      metadata: { amount: result.amount, currency: result.currency },
    });

    return result;
  }
}

Complete example

Here is a complete example showing AuditKit integrated into a NestJS application with authentication logging, data access tracking, and explicit event capture.

TypeScript
import { Module } from '@nestjs/common';
import { AuditKitModule, AuditLog, AuditKitService } from '@auditkit/nestjs';
import { ConfigService } from '@nestjs/config';

// Module setup with async configuration
@Module({
  imports: [
    AuditKitModule.forRootAsync({
      useFactory: (config: ConfigService) => ({
        apiKey: config.get('AUDITKIT_API_KEY'),
        tenantResolver: (req) => req.user?.organizationId,
        defaultContext: (req) => ({
          ipAddress: req.ip,
          userAgent: req.headers['user-agent'],
        }),
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

// Controller with decorator-based logging
@Controller('documents')
export class DocumentsController {
  constructor(private readonly auditkit: AuditKitService) {}

  @Get(':id')
  @AuditLog({
    action: 'document.viewed',
    targetType: 'document',
    targetId: (req) => req.params.id,
  })
  async getDocument(@Param('id') id: string) {
    return this.documentsService.findOne(id);
  }

  @Delete(':id')
  async deleteDocument(
    @Param('id') id: string,
    @Request() req,
  ) {
    const doc = await this.documentsService.findOne(id);
    await this.documentsService.delete(id);

    await this.auditkit.log({
      action: 'document.deleted',
      actor: { id: req.user.id, email: req.user.email },
      target: { type: 'document', id },
      metadata: {
        documentTitle: doc.title,
        deletedAt: new Date().toISOString(),
      },
    });
  }
}

Common patterns

@AuditLog() decorator for declarative controller-level logging

AuditKitService injection for programmatic logging in services

Global interceptor for blanket API request logging

Guard integration for authentication event capture

CQRS event handler integration for domain event logging

Multi-tenant resolver for automatic tenant isolation

Frequently asked questions

How do I add audit logging to a NestJS application?

Install @auditkit/nestjs, register AuditKitModule.forRootAsync() in your AppModule, then use the @AuditLog() decorator on controller methods or inject AuditKitService into any provider for programmatic logging.

Does AuditKit work with NestJS guards and interceptors?

Yes. AuditKit provides a global interceptor that can automatically log all API requests. It also integrates with NestJS guards to capture authentication events and with exception filters to log error events.

More integration guides

Related resources

Add audit logging to your NestJS app

Get started with tamper-proof audit trails in minutes. Open source, from $99/mo.