Skip to content

WebSocketServer

reference
1 min readUpdated

Kind: Function

Source: packages/websockets/decorators/gateway-server.decorator.ts

Part of: Websockets

Attaches native Web Socket Server to a given property.

WebSocketServer() is a property decorator that attaches the underlying native WebSocket server instance to a gateway class property. Nest initializes the property after the gateway is created, allowing gateway methods to emit events, broadcast messages, or access adapter-specific server APIs.

Signature

ts
function WebSocketServer(): PropertyDecorator

Returns: PropertyDecorator

Diagram

mermaid
graph LR
  A[WebSocketGateway] --> B[WebSocketServer Decorator]
  B --> C[Gateway Server Property]
  D[Nest WebSockets Runtime] --> E[Create Native Server]
  E --> C
  C --> F[Emit or Broadcast Events]

Usage

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

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

  @SubscribeMessage('message')
  handleMessage(client: Socket, payload: { text: string }) {
    this.server.emit('message', {
      from: client.id,
      text: payload.text,
    });
  }
}

AI Coding Instructions

  • Use @WebSocketServer() only on gateway class properties decorated with @WebSocketGateway().
  • Type the decorated property with the native server implementation used by the configured adapter, such as Socket.IO's Server.
  • Do not manually instantiate or assign the server property; Nest populates it during gateway initialization.
  • Use the injected server for server-wide operations such as emit, room broadcasting, and adapter-specific APIs.
  • Ensure event handlers account for the selected WebSocket adapter, since native server APIs differ between Socket.IO and ws.

Used by

2 references from 2 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (2)

  • EventsGatewaysample/02-gateways/src/events/events.gateway.ts:12
  • EventsGatewaysample/16-gateways-ws/src/events/events.gateway.ts:11

Was this page helpful?

Download as PDF
WebSocketServer — NestJS head-to-head