0
0
NestJSframework~30 mins

WebSocket gateway creation in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
WebSocket Gateway Creation with NestJS
📖 Scenario: You are building a simple chat server using NestJS. The server will use WebSocket to allow real-time communication between clients.
🎯 Goal: Create a WebSocket gateway in NestJS that listens for client connections and messages, then broadcasts received messages to all connected clients.
📋 What You'll Learn
Create a WebSocket gateway class named ChatGateway
Use the @WebSocketGateway() decorator on the ChatGateway class
Add a method named handleMessage that listens for message events
Broadcast received messages to all connected clients using this.server.emit
💡 Why This Matters
🌍 Real World
Real-time chat applications, live notifications, and collaborative tools use WebSocket gateways to enable instant communication between clients and servers.
💼 Career
Understanding WebSocket gateways in NestJS is essential for backend developers building scalable real-time applications and services.
Progress0 / 4 steps
1
Create the WebSocket Gateway Class
Create a class named ChatGateway and decorate it with @WebSocketGateway() from @nestjs/websockets.
NestJS
Need a hint?

Use @WebSocketGateway() decorator above the class declaration.

2
Add a Server Property
Inside the ChatGateway class, add a public property named server with the type any and decorate it with @WebSocketServer() from @nestjs/websockets.
NestJS
Need a hint?

The @WebSocketServer() decorator injects the WebSocket server instance.

3
Add a Message Handler Method
Add a method named handleMessage inside ChatGateway that listens for message events using the @SubscribeMessage('message') decorator. The method should accept a parameter named payload of type string.
NestJS
Need a hint?

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

4
Broadcast Received Messages
Inside the handleMessage method, use this.server.emit to broadcast the received payload to all connected clients with the event name message.
NestJS
Need a hint?

Use this.server.emit('message', payload) to send the message to all clients.