Unlock Real-Time Magic in Your App with NestJS and socket.io! ??
Kaleab Endrias
Backend Developer | Node.js & Python Enthusiast | ALX Software Engineering Graduate | Building Scalable Systems & Real-Time Applications
Enhance Your App with Real-Time Features Using NestJS! ??
Here’s a straightforward guide on how to implement real-time communication with WebSockets in NestJS, using the example code provided:
1. Set Up the WebSocket Gateway
Start by setting up the WebSocket gateway with the @WebSocketGateway({ cors: { origin: '*' } }) decorator. This configuration allows your WebSocket server to accept connections from any domain, making it accessible from different origins and ensuring seamless integration with various clients.
In the class, the @WebSocketServer() server: Server; decorator injects the WebSocket server instance, allowing you to interact with the server directly. This access is essential for emitting messages and managing connections across all clients
@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway {
@WebSocketServer() server: Server;
2. Initialize the Server
The afterInit(server: Server) method is called once your WebSocket server is initialized. Use this method to perform any necessary setup tasks or to log a message confirming that the server is ready. It’s your opportunity to ensure everything is in place before clients start connecting.
afterInit(server: Server) {
console.log('Websocket initialized');
}
3. Handle Client Connections
The handleConnection(client: Socket) method is triggered whenever a new client connects to the WebSocket server. This function allows you to handle new connections, such as logging client details or initializing client-specific settings.
领英推荐
handleConnection(client: Socket) {
console.log(`client connected ${client.id}`);
}
4. Process Incoming Messages
The @SubscribeMessage('message') decorator listens for messages with the event name 'message'. Inside the handleMessage(client: Socket, payload: any) method, you process these messages and broadcast them to all connected clients. This enables real-time communication, as you can send updates or notifications instantly.
@SubscribeMessage('message')
handleMessage(client: Socket, payload: any) {
this.server.emit('receiveMessage', { data: { payload } });
console.log(payload);
}
final code:
import {
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway {
@WebSocketServer() server: Server;
afterInit(server: Server) {
console.log('Websocket initialized');
}
handleConnection(client: Socket) {
console.log(`client connected ${client.id}`);
}
@SubscribeMessage('message')
handleMessage(client: Socket, payload: any) {
this.server.emit('receiveMessage', { data: { payload } });
console.log(payload);
}
}
Why Real-Time Features Matter
Incorporating real-time communication into your app can significantly enhance user engagement. Whether you’re building chat applications, live notifications, or interactive features, WebSockets provide the instant connectivity and updates that keep users connected and informed.
Leverage NestJS and WebSockets to bring these dynamic features to your app and create a more engaging user experience!
Thank you!