Bird
Raised Fist0
NestJSframework~10 mins

Event handling in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Event handling
Event Occurs
↓
Event Emitter emits event
↓
Event Listener catches event
↓
Listener executes handler function
↓
Handler processes event data
↓
Optional: Emit another event or update state
↓
End
This flow shows how an event is emitted, caught by a listener, and handled step-by-step in NestJS.
Execution Sample
NestJS
import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class MyService {
  constructor(private eventEmitter: EventEmitter2) {}

  triggerEvent() {
    this.eventEmitter.emit('user.created', { id: 1, name: 'Anna' });
  }

  @OnEvent('user.created')
  handleUserCreatedEvent(payload: { id: number; name: string }) {
    console.log(`User created: ${payload.name}`);
  }
}
This code emits a 'user.created' event and listens for it to log the user's name.
Execution Table
StepActionEvent NamePayloadListener CalledHandler Output
1Call triggerEvent()No
2Emit eventuser.created{ id: 1, name: 'Anna' }No
3Event caught by listeneruser.created{ id: 1, name: 'Anna' }Yes
4Handler executesuser.created{ id: 1, name: 'Anna' }YesUser created: Anna
5Event handling completeNo
💡 Event emitted and handled successfully, no more listeners.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
eventEmitterEventEmitter2 instanceEmitted 'user.created'Event caughtHandler processed payloadIdle
payloadundefined{ id: 1, name: 'Anna' }{ id: 1, name: 'Anna' }{ id: 1, name: 'Anna' }undefined
Key Moments - 3 Insights
Why doesn't the handler run before the event is emitted?
The handler only runs after the eventEmitter emits the event, as shown in steps 2 and 3 of the execution_table.
Can multiple listeners handle the same event?
Yes, multiple listeners can subscribe to the same event name and all will run when the event is emitted.
What happens if no listener is registered for an event?
The event is emitted but no handler runs, so no output or side effects occur.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the event listener catch the event?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Check the 'Listener Called' column in the execution_table.
What is the handler output when the 'user.created' event is handled?
ANo output
BUser created: id 1
CUser created: Anna
DError thrown
💡 Hint
Look at the 'Handler Output' column in step 4 of the execution_table.
If the eventEmitter.emit call is removed, what happens in the execution_table?
AListener never called, no handler output
BListener called anyway
CHandler runs with empty payload
DError occurs
💡 Hint
Refer to the flow: event must be emitted to trigger listeners.
Concept Snapshot
NestJS Event Handling:
- Use EventEmitter2 to emit events.
- Decorate methods with @OnEvent('event.name') to listen.
- Emitting triggers all listeners for that event.
- Handlers receive event payloads.
- Useful for decoupling parts of your app.
Full Transcript
In NestJS, event handling works by emitting events using EventEmitter2. When an event is emitted, all listeners registered with @OnEvent for that event name catch it and run their handler functions. The handler receives the event payload and can process it, such as logging or triggering other actions. This flow allows different parts of the app to communicate without tight connections. The execution table shows the steps: calling the triggerEvent method emits the event, the listener catches it, and the handler logs the user name. Variables like eventEmitter and payload change state as the event flows through the system. Beginners often wonder why handlers don't run before emitting or what happens if no listeners exist. The visual quiz tests understanding of when listeners run and what outputs occur. This event pattern helps keep code organized and reactive.

Practice

(1/5)
1. What is the main purpose of event handling in a NestJS application?
easy
A. To allow different parts of the app to react to actions without being tightly connected
B. To directly call methods from other classes
C. To replace all HTTP requests with events
D. To store data permanently in the database

Solution

  1. Step 1: Understand event handling concept

    Event handling lets parts of an app respond to actions independently, avoiding tight coupling.
  2. Step 2: Compare options

    Only To allow different parts of the app to react to actions without being tightly connected describes this purpose correctly; others describe unrelated concepts.
  3. Final Answer:

    To allow different parts of the app to react to actions without being tightly connected -> Option A
  4. Quick Check:

    Event handling = loose coupling reaction [OK]
Hint: Event handling means reacting without tight connections [OK]
Common Mistakes:
  • Thinking event handling replaces HTTP requests
  • Confusing event handling with direct method calls
  • Assuming event handling stores data
2. Which decorator is used to mark a class as an event handler in NestJS?
easy
A. @HandleEvent
B. @EventListener
C. @EventsHandler
D. @EventSubscriber

Solution

  1. Step 1: Recall NestJS event handler syntax

    The correct decorator to mark event handler classes is @EventsHandler.
  2. Step 2: Verify options

    Options B, C, and D are not valid NestJS decorators for event handlers.
  3. Final Answer:

    @EventsHandler -> Option C
  4. Quick Check:

    @EventsHandler marks event handlers [OK]
Hint: Use @EventsHandler to mark event handler classes [OK]
Common Mistakes:
  • Using @EventListener which is not a NestJS decorator
  • Confusing with @HandleEvent which does not exist
  • Using @EventSubscriber which is from other frameworks
3. Given this event handler code, what will be logged when eventBus.publish(new UserCreatedEvent('Alice')) is called?
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';

export class UserCreatedEvent {
  constructor(public readonly username: string) {}
}

@EventsHandler(UserCreatedEvent)
export class UserCreatedHandler implements IEventHandler<UserCreatedEvent> {
  handle(event: UserCreatedEvent) {
    console.log(`User created: ${event.username}`);
  }
}
medium
A. User created: undefined
B. No output because eventBus.publish does nothing
C. Error: handle method missing
D. User created: Alice

Solution

  1. Step 1: Understand event publishing and handling

    Publishing UserCreatedEvent triggers UserCreatedHandler which logs the username.
  2. Step 2: Check the handle method output

    The handle method logs "User created: " plus the event's username, which is "Alice".
  3. Final Answer:

    User created: Alice -> Option D
  4. Quick Check:

    Event publish triggers handler log [OK]
Hint: Publishing event triggers handle() logging username [OK]
Common Mistakes:
  • Assuming username is undefined
  • Thinking handle method is missing
  • Believing eventBus.publish does nothing
4. What is wrong with this event handler code?
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';

export class OrderPlacedEvent {
  constructor(public readonly orderId: number) {}
}

@EventsHandler(OrderPlacedEvent)
export class OrderPlacedHandler implements IEventHandler<OrderPlacedEvent> {
  handle() {
    console.log('Order placed:', orderId);
  }
}
medium
A. The handle method is missing the event parameter
B. The @EventsHandler decorator is used incorrectly
C. The event class should not have a constructor
D. The console.log syntax is invalid

Solution

  1. Step 1: Check handle method signature

    The handle method must accept the event parameter to access event data.
  2. Step 2: Identify usage of event data

    Inside handle, orderId is used but not defined because event parameter is missing.
  3. Final Answer:

    The handle method is missing the event parameter -> Option A
  4. Quick Check:

    handle(event) needs event parameter [OK]
Hint: handle() must receive event parameter to access data [OK]
Common Mistakes:
  • Omitting event parameter in handle method
  • Misusing @EventsHandler decorator
  • Thinking constructor is not needed in event class
5. You want to handle two different events, UserCreatedEvent and UserDeletedEvent, in one handler class. Which approach correctly implements this in NestJS?
hard
A. Use @EventsHandler without parameters and check event type inside handle method
B. Use @EventsHandler(UserCreatedEvent, UserDeletedEvent) on one class and implement handle(event) with type checks
C. Use @EventsHandler on one class but implement two separate handle methods named handleUserCreated and handleUserDeleted
D. Create two separate handler classes each with @EventsHandler for one event

Solution

  1. Step 1: Understand multiple event handling in one class

    In NestJS, you can pass multiple event classes to @EventsHandler decorator on one class.
  2. Step 2: Implement single handle method with event type checks

    The handle method receives any event instance; inside it, you check the event type to handle accordingly.
  3. Final Answer:

    Use @EventsHandler(UserCreatedEvent, UserDeletedEvent) on one class and implement handle(event) with type checks -> Option B
  4. Quick Check:

    Multiple events in one handler use @EventsHandler(...events) [OK]
Hint: Use @EventsHandler with multiple events and one handle method [OK]
Common Mistakes:
  • Trying to define multiple handle methods in one class
  • Creating separate classes instead of one combined handler
  • Using @EventsHandler without parameters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard