0
0
NestJSframework~5 mins

Why WebSockets enable real-time features in NestJS

Choose your learning style9 modes available
Introduction

WebSockets let your app talk back and forth with the server instantly. This helps build features that update right away without waiting.

Chat apps where messages appear instantly
Live sports scores updating without refreshing
Online games needing quick player moves
Real-time notifications like alerts or messages
Collaborative tools where many users edit together
Syntax
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway()
export class MyGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: string, client: Socket): void {
    this.server.emit('message', data);
  }
}

@WebSocketGateway() marks the class as a WebSocket handler.

@SubscribeMessage('event') listens for messages named 'event'.

Examples
This listens for 'chat' messages and sends the same message back.
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';

@WebSocketGateway()
export class ChatGateway {
  @SubscribeMessage('chat')
  onChat(@MessageBody() message: string) {
    return message;
  }
}
This gateway can send 'alert' messages to all connected clients anytime.
NestJS
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';

@WebSocketGateway()
export class NotifyGateway {
  @WebSocketServer()
  server: Server;

  sendAlert(alert: string) {
    this.server.emit('alert', alert);
  }
}
Sample Program

This simple gateway listens for 'ping' messages and replies with 'pong' plus the sent data. It shows how WebSockets enable instant two-way communication.

NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';

@WebSocketGateway()
export class RealTimeGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('ping')
  handlePing(@MessageBody() data: string) {
    return 'pong: ' + data;
  }
}
OutputSuccess
Important Notes

WebSockets keep the connection open, so messages flow instantly both ways.

They are better than regular requests when you want live updates without delays.

Summary

WebSockets create a live link between client and server.

This link lets apps update data immediately.

NestJS makes it easy to build WebSocket features with decorators.