04 / 06

How does the request lifecycle behave differently for WebSocket gateways vs HTTP controllers in NestJS?

WebSocket gateways support guards, interceptors, pipes, and filters but not middleware — middleware is HTTP-only. Guards use ctx.switchToWs().getClient() to access the socket. Exception filters use host.switchToWs(). The same enhancer class can support both HTTP and WebSocket by checking ctx.getType().

WebSocket gateway with guards, pipes, and filters
HTTP vs WebSocket lifecycle differences:
  1. 1

    Middleware — HTTP only; WebSocket connections skip the middleware layer entirely.

  2. 2

    Guards — supported on gateways; use ctx.switchToWs().getClient() for socket access.

  3. 3

    Interceptors — supported on gateways; wrap @SubscribeMessage handlers.

  4. 4

    Pipes — supported on @MessageBody() and @ConnectedSocket() parameters.

  5. 5

    Filters — supported; use host.switchToWs() to access the socket and data.

  6. 6

    WsException should be thrown in WebSocket context instead of HttpException.