- Published
- Author
- Puneeth kumarSystem Analyst
Using
In NestJS, event-based communication can be implemented using
How to use it?
• Install the necessary package:
• Register the module in the app:
• Emit an event from anywhere in the app:
• Handle the event using a listener:
Why use emits?
✅ Decouples the core logic from side-effects
✅ Makes it easier to add/remove behaviours like notifications, logging
✅ Encourages modular architecture
#CCT1JMA0Z #nestJs #event_based_communication
emit in NestJSIn NestJS, event-based communication can be implemented using
@nestjs/event-emitter package, which is built on top of eventemitter2 . It's particularly useful for decoupling the parts of our application — for example, sending notifications, logging, or triggering async jobs after certain actions.How to use it?
• Install the necessary package:
Code
npm install --save @nestjs/event-emitter• Register the module in the app:
Code
// app.module.ts
import { EventEmitterModule } from '@nestjs/event-emitter';
@Module({
imports: [
EventEmitterModule.forRoot(),
],
})
export class AppModule {}• Emit an event from anywhere in the app:
Code
// user.service.ts
import { EventEmitter2 } from '@nestjs/event-emitter';
@Injectable()
export class UserService {
constructor(private eventEmitter: EventEmitter2) {}
async createUser(userDto: CreateUserDto) {
const user = await this.userRepository.save(userDto);
this.eventEmitter.emit('user.created', user); // 🔥
return user;
}
}• Handle the event using a listener:
Code
// user.listener.ts
import { OnEvent } from '@nestjs/event-emitter';
@Injectable()
export class UserListener {
@OnEvent('user.created')
handleUserCreatedEvent(payload: any) {
console.log('User created!', payload);
// Trigger welcome email, analytics, etc.
}
}Why use emits?
✅ Decouples the core logic from side-effects
✅ Makes it easier to add/remove behaviours like notifications, logging
✅ Encourages modular architecture
#CCT1JMA0Z #nestJs #event_based_communication