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.

info 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. @@filename()
  2. @UseGuards(AuthGuard)
  3. @SubscribeMessage('events')
  4. handleEvent(client: Client, data: unknown): WsResponse<unknown> {
  5. const event = 'events';
  6. return { event, data };
  7. }
  8. @@switch
  9. @UseGuards(AuthGuard)
  10. @SubscribeMessage('events')
  11. handleEvent(client, data) {
  12. const event = 'events';
  13. return { event, data };
  14. }