Skip to main content

Emit and listen to events

Suppose you need to send an email when a user is created, or you want to issue a notification each time a message is sent. The events feature in the back-end is designed to manage these kinds of events efficiently.

Emit an event

import { EventEmitter2 } from '@nestjs/event-emitter'

const eventEmitter = new EventEmitter2()
this.eventEmitter.emit('message.sent', {
userId: '123-123',
message: 'A cool message',
})

Listen to an event

Create an subscriber

We recommend to organise your events under an infrastructure folder in each module of the back-end.

/server/modules/notification
/application
/domain
/infrastructure
/subscribers
notification.messageSent.subscriber.ts
notification.commentPosted.subscriber.ts

Create a file notification.messageSent.subscriber.ts

import { Injectable } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { OrderCreatedEvent } from '../events/order-created.event'

@Injectable()
export class NotificationMessageSentSubscriber {
@OnEvent('message.sent')
handleMessageSentEvent(event: { userId: string; message: string }) {
// handle and process "MessageSentEvent" event to create the notification
console.log(event)
}
}

Import your subscriber

In the module /src/modules/notification/subscription.module.ts, don't forget to add all your different subscribers to the providers array.

export class NotificationModule extends CoreModule {
controllers = [NotificationController, NotificationByMeController]
modules = []
providers = [NotificationMessageSentSubscriber]
}