NestJS

WebSockets

Real-time bidirectional communication using WebSockets and Socket.io in NestJS.

Events Gateway: Creating a WebSocket gateway to listen for and emit events.
📄events.gateway.ts
typescript
import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  handleConnection(client: Socket) {
    console.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    console.log(`Client disconnected: ${client.id}`);
  }

  @SubscribeMessage('events')
  handleEvent(@MessageBody() data: string): string {
    // Broadcast message to all clients
    this.server.emit('message', { msg: `New event: ${data}` });
    return data;
  }
}
Gateway Module: Registering the gateway as a provider in a module.
📄events.module.ts
typescript
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class EventsModule {}