0
0
NestJSframework~30 mins

Gateway decorator in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the WebSocketGateway Decorator in NestJS
📖 Scenario: You are building a simple chat server using NestJS. You want to create a WebSocket gateway that listens for client connections and messages.
🎯 Goal: Create a WebSocket gateway using the @WebSocketGateway decorator in NestJS. This gateway will handle client connections and messages.
📋 What You'll Learn
Create a class named ChatGateway
Use the @WebSocketGateway decorator on the ChatGateway class
Add a method named handleMessage that will receive messages
Use the @SubscribeMessage decorator on the handleMessage method
💡 Why This Matters
🌍 Real World
WebSocket gateways are used in real-time applications like chat apps, live notifications, and multiplayer games to handle live communication between clients and servers.
💼 Career
Understanding how to use the WebSocketGateway decorator in NestJS is essential for backend developers working on real-time features and WebSocket-based services.
Progress0 / 4 steps
1
Create the ChatGateway class with the WebSocketGateway decorator
Create a class called ChatGateway and decorate it with @WebSocketGateway() from @nestjs/websockets.
NestJS
Need a hint?

Remember to import WebSocketGateway from @nestjs/websockets and use it as a decorator above the class.

2
Add the SubscribeMessage decorator import and message handler method
Import SubscribeMessage from @nestjs/websockets and add a method named handleMessage inside ChatGateway.
NestJS
Need a hint?

Use @SubscribeMessage('message') above the handleMessage method to listen for 'message' events.

3
Implement the handleMessage method to return the received payload
Inside the handleMessage method, return the payload parameter.
NestJS
Need a hint?

Simply return the payload to send it back to the client.

4
Export the ChatGateway class as default export
Add export default ChatGateway; at the end of the file to export the class as default.
NestJS
Need a hint?

Use export default ChatGateway; to make the class available for import elsewhere.