@elchinabilov/nestjs-audit-logs
v1.2.8
Published
NestJS audit log module with TypeORM and CLS context
Maintainers
Readme
@elchinabilov/nestjs-audit-logs
NestJS audit log module for TypeORM with CLS context support.
Features
- TypeORM entity and service for storing audit logs
- Interceptor that captures request metadata
- Decorator for per-route metadata
- CLS integration via
nestjs-cls(installed automatically)
Installation
npm install @elchinabilov/nestjs-audit-logsPeer dependencies
Make sure your app has these installed:
@nestjs/common@nestjs/core@nestjs/typeormtypeormrxjsclass-validator
nestjs-cls is a direct dependency and will be installed automatically.
Usage
1) Import the module
import { Module } from "@nestjs/common";
import { AuditLogModule } from "@elchinabilov/nestjs-audit-logs";
@Module({
imports: [AuditLogModule.forRoot()],
})
export class AppModule {}Optional: use a separate (external) DB for audit logs
AuditLogModule.forRoot({
connectionName: "auditLogs",
typeOrmModuleOptions: {
type: "postgres",
host: "localhost",
port: 5432,
username: "audit_user",
password: "audit_pass",
database: "audit_db",
// If you pass `entities` as a glob string, keep `autoLoadEntities: true`
// or include `AuditLogEntity` in your entities list.
},
// Auto-creates the audit_logs table for this connection (default: true)
// Set to false if you prefer running migrations manually.
autoCreateTable: true,
});2) Ensure the entity is registered (default connection only)
If you use autoLoadEntities: true, it will be picked up automatically. Otherwise, add AuditLogEntity to your TypeORM entities.
import { TypeOrmModule } from "@nestjs/typeorm";
import { AuditLogEntity } from "@elchinabilov/nestjs-audit-logs";
TypeOrmModule.forRoot({
// ...
entities: [AuditLogEntity],
});3) Register the interceptor
You can apply it globally or per-controller.
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuditLogInterceptor } from '@elchinabilov/nestjs-audit-logs';
providers: [
{
provide: APP_INTERCEPTOR,
useClass: AuditLogInterceptor,
},
],4) Add AuditLog decorator
Only routes decorated with @AuditLog() will be logged.
import { AuditLog } from '@elchinabilov/nestjs-audit-logs';
@AuditLog({ module: 'users' })
@Get('users')
findAll() {}5) Set CLS values
The interceptor reads userId, role, and requestId from the CLS context. Populate these values in a guard, middleware, or interceptor before the audit interceptor runs.
import { ExecutionContext, Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { ClsService } from "nestjs-cls";
import { v4 as uuid } from "uuid";
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {
constructor(
// Add this line
private readonly cls: ClsService
) {
super();
}
canActivate(context: ExecutionContext) {
// ...
}
// Add this code block
handleRequest(err, user, info, context: ExecutionContext) {
const req = context.switchToHttp().getRequest();
if (user) {
this.cls.set("userId", user.id);
this.cls.set("role", user.role?.name);
}
this.cls.set("requestId", uuid());
return user;
}
}Notes
The module calls
ClsModule.forRoot({ global: true, middleware: { mount: true } })internally.Logs are stored in the
audit_logstable.AuditLogService.find()supports pagination viapageandlimitin filters (defaults: page 1, limit 25).When
typeOrmModuleOptionsis provided, the module enables table auto-creation by default (autoCreateTable: true). SetautoCreateTable: false(orsynchronize: false) to disable it.If you use the default app connection, use TypeORM
synchronizeor migrations to create the table.Run the following command to create migration file
npx @elchinabilov/nestjs-audit-logs migration:copy
Description: Copies audit log migrations into your project with timestamped class names.
- Final run:
npm run migration:run
