Gateways and Socket.IO

Why WebSockets

HTTP is request-response: the client must ask. For live order tracking, chat or stock tickers, the server needs to push updates. A WebSocket keeps one connection open in both directions. NestJS uses gateways (Socket.IO by default).

Example

npm i @nestjs/websockets @nestjs/platform-socket.io socket.io

Example output

added 21 packages in 4s

A Gateway

src/orders/orders.gateway.ts

import {
  ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect,
  SubscribeMessage, WebSocketGateway, WebSocketServer,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ namespace: '/orders', cors: { origin: ['https://shopease.in', 'http://localhost:3001'] } })
export class OrdersGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;
  private readonly logger = new Logger(OrdersGateway.name);

  handleConnection(client: Socket) {
    this.logger.log(`connected ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`disconnected ${client.id}`);
  }

  @SubscribeMessage('order:track')
  track(@MessageBody() data: { orderId: string }, @ConnectedSocket() client: Socket) {
    client.join(`order:${data.orderId}`);              // a room per order
    return { event: 'order:tracking', data: { orderId: data.orderId } };   // ack to this client
  }

  // called by OrdersService when the status changes
  emitStatus(orderId: string, status: string, etaMinutes?: number) {
    this.server.to(`order:${orderId}`).emit('order:status', { orderId, status, etaMinutes });
  }
}

Add OrdersGateway to the providers of OrdersModule. It runs on the same port as the HTTP API.