🦅 NestJS Intermediate

What is event-driven architecture in NestJS using the EventEmitter?

Answer

NestJS provides the @nestjs/event-emitter module for event-driven patterns within a single application (not between microservices). Import EventEmitterModule.forRoot(). Emit events: this.eventEmitter.emit('user.created', new UserCreatedEvent(user)). Listen with: @OnEvent('user.created') handleUserCreated(payload: UserCreatedEvent) { ... }. The @OnEvent() decorator registers the method as an event handler. Events are dispatched synchronously by default; use EventEmitterModule.forRoot({ global: true, async: true }) for async dispatch. This pattern decouples side effects (sending welcome emails, updating caches) from the primary operation (creating a user), enabling the single-responsibility principle without introducing a full message broker for intra-service communication.