How to Use Event Emitter in NestJS: Simple Guide
In NestJS, use the built-in
EventEmitter2 package to emit and listen to events by injecting EventEmitter2 service. Emit events with emit() and listen using @OnEvent() decorator in your services or controllers.Syntax
To use event emitter in NestJS, first import and inject EventEmitter2 from @nestjs/event-emitter. Use emit(eventName, payload) to send events. Use @OnEvent(eventName) decorator on methods to listen for events.
EventEmitter2: The service to emit events.emit(eventName, payload): Sends an event with a name and optional data.@OnEvent(eventName): Decorator to mark event listener methods.
typescript
import { Injectable } from '@nestjs/common'; import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'; @Injectable() export class MyService { constructor(private eventEmitter: EventEmitter2) {} triggerEvent() { this.eventEmitter.emit('my.event', { message: 'Hello' }); } @OnEvent('my.event') handleMyEvent(payload: any) { console.log('Event received:', payload); } }
Example
This example shows a service emitting an event and another service listening to it. When triggerEvent() is called, the listener logs the event payload.
typescript
import { Injectable } from '@nestjs/common'; import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'; @Injectable() export class EmitterService { constructor(private eventEmitter: EventEmitter2) {} triggerEvent() { this.eventEmitter.emit('user.created', { userId: 123, name: 'Alice' }); } } @Injectable() export class ListenerService { @OnEvent('user.created') handleUserCreatedEvent(payload: { userId: number; name: string }) { console.log(`User created with ID: ${payload.userId} and name: ${payload.name}`); } } // Usage example (e.g., in a controller or main app): // const emitter = new EmitterService(eventEmitterInstance); // emitter.triggerEvent();
Output
User created with ID: 123 and name: Alice
Common Pitfalls
Common mistakes when using event emitter in NestJS include:
- Not importing
EventEmitterModulein your module, so the event emitter service is not available. - Forgetting to decorate listener methods with
@OnEvent(), so events are not caught. - Using string event names inconsistently, causing listeners to miss events.
- Not handling asynchronous listeners properly if needed.
typescript
/* Wrong: Missing EventEmitterModule import */ // @Module({ // providers: [EmitterService, ListenerService], // }) // export class AppModule {} /* Right: Import EventEmitterModule */ import { Module } from '@nestjs/common'; import { EventEmitterModule } from '@nestjs/event-emitter'; @Module({ imports: [EventEmitterModule.forRoot()], providers: [EmitterService, ListenerService], }) export class AppModule {}
Quick Reference
Summary tips for using EventEmitter in NestJS:
- Always import
EventEmitterModule.forRoot()in your root module. - Inject
EventEmitter2to emit events. - Use
@OnEvent('event.name')to listen to events. - Keep event names consistent and descriptive.
- Listeners can be async if needed.
Key Takeaways
Import EventEmitterModule.forRoot() in your module to enable event emitting.
Inject EventEmitter2 service to emit events with emit(eventName, payload).
Use @OnEvent(eventName) decorator on methods to listen for events.
Keep event names consistent to ensure listeners receive events.
Listeners can be asynchronous to handle async operations.