Skip to content

WebSocketsController

reference
4 min readUpdated

Kind: Class

Source: packages/websockets/web-sockets-controller.ts

Part of: Websockets

WebSocketsController is the framework-level coordinator that discovers WebSocket gateway entrypoints and connects them to the configured socket server. It subscribes gateway lifecycle hooks (init, connection, disconnect) and message handlers, then normalizes handler results into observables for transport delivery.

Methods

MethodSignatureReturns
connectGatewayToServer`connectGatewayToServer(instance: NestGateway, metatype: TypeFunction, moduleKey: string, instanceWrapperId: string)`
subscribeToServerEventssubscribeToServerEvents(instance: NestGateway, options: T, port: number, moduleKey: string, instanceWrapperId: string)void
subscribeEventssubscribeEvents(instance: NestGateway, subscribersMap: MessageMappingProperties[], observableServer: ServerAndEventStreamsHost)void
getConnectionHandlergetConnectionHandler(context: WebSocketsController, instance: NestGateway, subscribersMap: MessageMappingProperties[], disconnect: Subject<any>, connection: Subject<any>)void
subscribeInitEventsubscribeInitEvent(instance: NestGateway, event: Subject<any>)void
subscribeConnectionEventsubscribeConnectionEvent(instance: NestGateway, event: Subject<any>)void
subscribeDisconnectEventsubscribeDisconnectEvent(instance: NestGateway, event: Subject<any>)void
subscribeMessagessubscribeMessages(subscribersMap: MessageMappingProperties[], client: T, instance: NestGateway)void
pickResultpickResult(deferredResult: Promise<any>)Promise<Observable<any>>
inspectEntrypointDefinitionsinspectEntrypointDefinitions(instance: NestGateway, port: number, messageHandlers: MessageMappingProperties[], instanceWrapperId: string)void

Where it refuses work

  • WebSocketsController stops the work with InvalidSocketPortException when !Number.isInteger(port).
  • WebSocketsController stops the work with an early return when this.appOptions.preview.
  • WebSocketsController stops the work with an early return when isObservable(result).
  • WebSocketsController stops the work with an early return when result instanceof Promise.
  • WebSocketsController stops the work with an early return when !gatewayClassName.

Diagram

mermaid
graph LR
  A[Gateway Provider] --> B[WebSocketsController]
  B --> C[inspectEntrypointDefinitions]
  B --> D[connectGatewayToServer]
  D --> E[Socket Server]
  B --> F[subscribeToServerEvents]
  F --> G[subscribeInitEvent]
  F --> H[subscribeConnectionEvent]
  F --> I[subscribeDisconnectEvent]
  F --> J[subscribeMessages]
  J --> K[getConnectionHandler]
  K --> L[pickResult]
  L --> M[Observable Response]
  E --> N[Connected Clients]

Usage

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

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  @WebSocketServer()
  server: Server;

  handleConnection(client: Socket) {
    console.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    console.log(`Client disconnected: ${client.id}`);
  }

  @SubscribeMessage('chat:message')
  handleMessage(client: Socket, payload: { text: string }) {
    return {
      event: 'chat:message',
      data: {
        clientId: client.id,
        text: payload.text,
      },
    };
  }
}

// WebSocketsController is created by Nest internally during application startup.
// It discovers ChatGateway, attaches it to the Socket.IO server, subscribes to
// lifecycle events, and routes "chat:message" events to handleMessage().

AI Coding Instructions

  • Treat WebSocketsController as framework infrastructure; applications should define gateways and message handlers rather than instantiate this class directly.
  • Keep gateway event handlers compatible with the result pipeline: return values that can be converted into observable WebSocket responses when appropriate.
  • When adding lifecycle behavior, preserve the separate initialization, connection, and disconnect subscription paths.
  • Ensure new gateway entrypoint metadata can be discovered by inspectEntrypointDefinitions() and connected through connectGatewayToServer().
  • Avoid subscribing message handlers more than once for the same gateway/server pair, as this can cause duplicated client responses.

How it works

Role

WebSocketsController is the runtime coordinator that connects a gateway instance to a WebSocket server, discovers its message-mapped methods, creates their WebSocket execution contexts, registers lifecycle callbacks, and binds client connections and message handlers through the configured I/O adapter. packages/websockets/web-sockets-controller.ts:29-43 packages/websockets/web-sockets-controller.ts:66-127

SocketModule constructs this controller during WebSocket-module registration and calls connectGatewayToServer() only for provider metatypes carrying GATEWAY_METADATA. packages/websockets/socket-module.ts:50-65 packages/websockets/socket-module.ts:77-94

Gateway connection and validation

Message mappings and entrypoint inspection

Preview mode and server setup

Lifecycle events and client connections

Message invocation and return values

Relationships

  • IMPORTS → NestApplicationContextOptions
  • IMPORTS → Type
  • IMPORTS → Logger
  • IMPORTS → ApplicationConfig
  • IMPORTS → GraphInspector
  • IMPORTS → MetadataScanner

Was this page helpful?

Download as PDF
WebSocketsController — NestJS head-to-head