Guards

There is no fundamental difference between web sockets guards and regular HTTP application guards. The only difference is that instead of throwing HttpException, you should use WsException.

Hint The WsException class is exposed from @nestjs/websockets package.

Binding guards

The following example uses a method-scoped guard. Just as with HTTP based applications, you can also use gateway-scoped guards (i.e., prefix the gateway class with a @UseGuards() decorator).

  1. @UseGuards(AuthGuard)
  2. @SubscribeMessage('events')
  3. handleEvent(client: Client, data: unknown): WsResponse<unknown> {
  4. const event = 'events';
  5. return { event, data };
  6. }
  1. @UseGuards(AuthGuard)
  2. @SubscribeMessage('events')
  3. handleEvent(client, data) {
  4. const event = 'events';
  5. return { event, data };
  6. }