0
0
NestJSframework~5 mins

Gateway decorator in NestJS

Choose your learning style9 modes available
Introduction

The Gateway decorator marks a class as a WebSocket gateway. It helps your app talk with clients in real-time using WebSockets.

You want to build a chat app where messages update instantly.
You need to send live notifications to users without page reloads.
You want to track live data like stock prices or game scores.
You want to handle real-time events from clients in your server.
You want to create multiplayer game servers that sync players quickly.
Syntax
NestJS
@WebSocketGateway(options?)
class YourGateway {
  // your methods here
}
The decorator is placed above a class to make it a WebSocket gateway.
You can pass options like port or namespace to customize the gateway.
Examples
A simple gateway with default settings.
NestJS
@WebSocketGateway()
class ChatGateway {}
Gateway listens on the '/chat' namespace.
NestJS
@WebSocketGateway({ namespace: '/chat' })
class ChatGateway {}
Gateway listens on port 3001 for WebSocket connections.
NestJS
@WebSocketGateway({ port: 3001 })
class NotificationGateway {}
Sample Program

This gateway listens on the '/chat' namespace. When a client sends a 'message' event, the server logs it and replies with a confirmation message.

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

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  @SubscribeMessage('message')
  handleMessage(@MessageBody() message: string, @ConnectedSocket() client: Socket): string {
    console.log(`Received message: ${message}`);
    return `Server says: ${message}`;
  }
}
OutputSuccess
Important Notes

Use the Gateway decorator only on classes meant to handle WebSocket events.

Namespaces help organize different WebSocket channels in your app.

Remember to import necessary decorators and types from '@nestjs/websockets'.

Summary

The Gateway decorator turns a class into a WebSocket gateway.

It enables real-time communication between server and clients.

You can customize it with options like namespace and port.