Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 42 ยท Beyond HTTP

WebSockets and Gateways

Build real-time features in NestJS with @WebSocketGateway: message handlers, rooms, guards and pipes on gateways, adapters, scaling with Redis, plus a loopback demo.

HTTP is a question-and-answer protocol: the client asks, the server replies, and the conversation ends. For a chat, a live score, a collaborative editor or a notification feed, you want the server to be able to push data whenever something happens. A WebSocket is a long-lived, two-way connection that starts as an HTTP request, is upgraded, and then lets either side send messages at any time.

In Nest, the building block is the gateway: a class decorated with @WebSocketGateway() whose methods handle incoming messages, a bit like a controller whose "routes" are message names. Gateways are ordinary providers, so they get dependency injection, and guards, pipes, interceptors and exception filters all apply to them.

The real packages need Node and npm, so the Nest snippets below are read-only. The runnable parts are stand-ins on a loopback connection: a small WebSocket server written with Node's built-in modules (handshake, frames, rooms) and a look at how frames are encoded.

HTTP vs WebSocket

HTTP Client asks, server answers, done.
WebSocket One open connection, both sides talk.

The connection starts as HTTP and is upgraded.

1 / 2

A first gateway

Install @nestjs/websockets and a platform package. The default is @nestjs/platform-socket.io (Socket.IO); @nestjs/platform-ws uses the plain ws library. A gateway looks like this:

TypeScript
import {
  ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayDisconnect,
  SubscribeMessage, WebSocketGateway, WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ cors: { origin: 'https://app.example.com' } })
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

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

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

  @SubscribeMessage('chat:send')
  onMessage(@MessageBody() body: { text: string }, @ConnectedSocket() client: Socket) {
    this.server.emit('chat:message', { from: client.id, text: body.text });
    return { ok: true }; // sent back to this client as an acknowledgement
  }
}

Register the class in a module's providers array and it starts with the app; by default it shares the HTTP server's port, or you can pass a port to @WebSocketGateway(3001).

  • @SubscribeMessage('chat:send') binds a method to an incoming message name, the way @Get() binds to a path.
  • @MessageBody() and @ConnectedSocket() inject the payload and the connection, like @Body() in a controller.
  • @WebSocketServer() injects the underlying server so you can send to everyone or to groups.
  • The OnGatewayConnection, OnGatewayDisconnect and OnGatewayInit interfaces give you lifecycle hooks.
  • A returned value becomes an acknowledgement for the sender (with Socket.IO) so the client knows the message was handled.

Messages are normally JSON objects with an event name and data. With the plain ws adapter, the default shape is { "event": "chat:send", "data": { ... } }. Socket.IO has its own protocol on top of WebSocket (with fallbacks, reconnection and acknowledgements built in), so a plain WebSocket client cannot talk to a Socket.IO server unless it speaks that protocol. Choose the adapter to match your clients.

Rooms

Sending to everyone is rarely what you want. A room is a named group of connections, such as chat:42 or user:7. A connection joins and leaves rooms, and you emit to a room instead of to all:

TypeScript
@SubscribeMessage('room:join')
async join(@MessageBody() roomId: string, @ConnectedSocket() client: Socket) {
  await client.join(`room:${roomId}`);
  this.server.to(`room:${roomId}`).emit('room:joined', { user: client.id });
}

@SubscribeMessage('room:message')
message(@MessageBody() body: { roomId: string; text: string }, @ConnectedSocket() client: Socket) {
  this.server.to(`room:${body.roomId}`).emit('room:message', { from: client.id, text: body.text });
}

join, leave and to(room) are Socket.IO features that the Socket.IO adapter exposes. The plain ws library has no rooms: you keep your own Map of room names to sockets, which is exactly what the stand-in below does.

An important security point: joining a room is not authorization. If any client can send room:join with any id, any client can listen to any room. Check in the handler that the user may join that room.

Guards, pipes and filters on gateways

The same pipeline pieces from Guards and Authorization, Pipes and Validation and Exception Filters work on gateways, with a few differences:

TypeScript
@UseGuards(WsAuthGuard)
@UsePipes(new ValidationPipe({ whitelist: true }))
@SubscribeMessage('chat:send')
onMessage(@MessageBody() dto: SendMessageDto) { /* ... */ }
  • In a guard, get the socket with context.switchToWs().getClient() and the payload with getData(), instead of switchToHttp().
  • Throw WsException('message') rather than HttpException. A gateway has no HTTP status code to return, so Nest turns a WsException into an error event for the client.
  • Validation pipes work on @MessageBody() DTOs, so you can reuse the same validation classes as in REST.

Authenticating the connection

A message-level guard runs for each message, but the connection itself should be authenticated once, when it opens. Browsers cannot set custom headers on a WebSocket handshake, so clients usually pass a token as a query parameter (which can end up in logs, so use a short-lived token) or in the first message, or rely on cookies. A common pattern is to verify the token in handleConnection (or in a middleware on the Socket.IO server), store the user on the socket, and disconnect clients that fail:

TypeScript
async handleConnection(client: Socket) {
  try {
    const token = client.handshake.auth?.token;
    client.data.user = await this.jwt.verifyAsync(token); // see the JWT lesson
  } catch {
    client.disconnect(true);
  }
}

The token logic is the same as in Authentication with JWT. Rejecting during the HTTP upgrade, before the connection exists, is even better, and the stand-in below does exactly that.

Adapters and scaling with Redis

Nest talks to the WebSocket library through an adapter. IoAdapter (Socket.IO) is the default and WsAdapter wraps ws. You can write your own adapter if you need a different library.

A single server process knows only its own connections. If you run three instances behind a load balancer, a user connected to instance A is invisible to a broadcast made on instance B. The standard fix with Socket.IO is the Redis adapter: instances publish room broadcasts through Redis pub/sub so each one forwards them to its own local sockets.

TypeScript
export class RedisIoAdapter extends IoAdapter {
  private adapterConstructor: ReturnType<typeof createAdapter>;

  async connectToRedis() {
    const pub = createClient({ url: 'redis://localhost:6379' });
    const sub = pub.duplicate();
    await Promise.all([pub.connect(), sub.connect()]);
    this.adapterConstructor = createAdapter(pub, sub);
  }

  createIOServer(port: number, options?: ServerOptions) {
    const server = super.createIOServer(port, options);
    server.adapter(this.adapterConstructor);
    return server;
  }
}

You install it in main.ts with app.useWebSocketAdapter(...). Two more scaling notes. Socket.IO's HTTP long-polling fallback needs sticky sessions at the load balancer (so each client keeps hitting the same instance), unless you force the WebSocket transport only. And every open connection costs memory and a file descriptor, so plan for graceful deploys: clients should reconnect automatically and resume (fetch missed messages by id) rather than assume a perfect connection.

Stand-in: a WebSocket server in plain Node

To see what a gateway does, the next demo builds a tiny WebSocket server on a loopback port with only node:http and node:crypto. It performs the real handshake (the Sec-WebSocket-Accept header), decodes masked client frames, keeps a Map of rooms and rejects a bad token during the upgrade, before any connection exists. The clients use Node's built-in WebSocket. This is not Nest or Socket.IO, and it supports only the simple case (complete text frames, no fragmentation), but the ideas are the same as in a gateway.

Node.js Rooms and an auth check on a loopback WebSocket server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The bad token never gets a connection, because the 401 is written during the upgrade. Ada and Bob share the lobby and both see Ada's message (the sender is in the room, so she receives her own broadcast too), while Cy, in a different room, sees nothing and gets an error when trying to speak in a room she never joined. That last check is the "joining is not authorization" lesson in code.

Stand-in: what a frame looks like

Under every WebSocket library, messages are frames with a small header. Clients must mask the payload with a random 4-byte key (so a proxy cannot be tricked into misreading it), while servers send unmasked frames. This offline demo builds a client frame by hand and decodes it, so you can see the header bytes. The mask is fixed here to keep the output stable; real clients use a fresh random one for every frame.

Node.js Masking and the frame header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first byte 0x81 means "final fragment, text frame". The second byte holds the mask bit plus the payload length, and a length of 126 means "the real length follows in the next two bytes". The masked bytes on the wire look nothing like the JSON, yet decoding with the same key gives the exact text back. Libraries do all of this for you; knowing it exists helps when you debug a connection in a network inspector.

Practical advice

  • Validate every message as you would an HTTP body. A socket client is as untrusted as a form post.
  • Authenticate once at connect time, authorize per action (joining rooms, sending to rooms).
  • Limit message size and rate. Throttling HTTP routes does not protect a socket, so add checks per connection.
  • Plan for reconnects. Networks drop. Give messages ids so clients can fetch what they missed.
  • Keep handlers thin. Call services so the logic works for both REST and sockets and stays testable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @SubscribeMessage('chat:send') do on a gateway method?

    SubscribeMessage maps a message (event) name to a handler, like a route decorator does for URLs.
  2. 2. Why is client.join('room:7') alone not a safe access control?

    Joining just adds a connection to a group. Authorization must be checked in the handler or a guard.
  3. 3. You run three instances of a Socket.IO app behind a load balancer and broadcasts miss some users. What is the usual fix?

    Each instance knows only its own sockets. The Redis adapter relays broadcasts between instances.
  4. 4. Which exception should a gateway handler throw to report an error to the client?

    WsException is turned into an error event for the socket client. HTTP status codes do not exist on a socket.
  5. 5. Why do browsers usually send an auth token as a query parameter or first message on WebSocket connections?

    The browser WebSocket constructor takes no custom headers, so tokens go in the URL, in a cookie, or in the first message.

Summary

  • A WebSocket is a long-lived, two-way connection upgraded from HTTP; a Nest gateway (@WebSocketGateway) handles its messages with @SubscribeMessage, @MessageBody and @ConnectedSocket.
  • @WebSocketServer() gives you the server for broadcasts; Socket.IO rooms group connections, while the plain ws library needs your own bookkeeping.
  • Guards, pipes, interceptors and filters apply to gateways; use switchToWs() in guards and WsException for errors.
  • Authenticate when the connection opens, authorize each action, and validate every message.
  • Adapters connect Nest to Socket.IO or ws; scale across instances with the Redis adapter and sticky sessions where needed.
  • Frames, masking and the handshake are handled by libraries, but the loopback stand-in shows what happens underneath.

Continue with Testing Nest Applications to learn how to verify all of this automatically.