0
0
NestJSframework~5 mins

WebSocket gateway creation in NestJS

Choose your learning style9 modes available
Introduction

A WebSocket gateway lets your app talk instantly with users without waiting for them to ask. It helps send and get messages in real time.

You want to build a chat app where messages appear instantly.
You need live updates on a dashboard without refreshing the page.
You want to notify users immediately when something changes.
You are making a multiplayer game that needs fast communication.
You want to stream data like stock prices or sports scores live.
Syntax
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';

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

  @SubscribeMessage('message')
  handleMessage(@MessageBody() data: string): string {
    return `Received: ${data}`;
  }
}

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

@SubscribeMessage('event') listens for messages with the given event name.

Examples
This listens for 'chat' messages and replies with a simple string.
NestJS
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';

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

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

  sendEvent() {
    this.server.emit('event', 'Hello everyone!');
  }
}
Sample Program

This gateway listens for a 'greet' message with a name and replies with a hello message including that name.

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

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

  @SubscribeMessage('greet')
  handleGreet(@MessageBody() name: string): string {
    return `Hello, ${name}!`;
  }
}
OutputSuccess
Important Notes

Make sure to install @nestjs/websockets and socket.io packages.

Use @WebSocketServer() to access the server and send messages to clients.

Event names in @SubscribeMessage() must match what clients send.

Summary

WebSocket gateways let your NestJS app handle real-time messages easily.

Use decorators to listen for and respond to events.

You can send messages back to one or all connected clients.