03 / 06

How do you write a single guard that works across both HTTP and WebSocket transports in NestJS?

Use ctx.getType() to detect the current transport and branch accordingly. For HTTP, extract the token from the Authorization header. For WebSocket, extract it from client.handshake.auth or handshake headers. Return true if verification succeeds, throw the transport-appropriate exception if not.

Universal auth guard for HTTP and WebSocket
Multi-transport guard design notes:
  1. 1

    ctx.getType() returns 'http', 'ws', or 'rpc' — always check before switching context.

  2. 2

    WebSocket tokens come from handshake.auth (Socket.IO) or handshake.headers.

  3. 3

    Store user on client.data.user for WebSocket — equivalent to req.user for HTTP.

  4. 4

    Throw WsException for WebSocket errors, not HttpException — they serialize differently.

  5. 5

    For microservice RPC use ctx.switchToRpc().getData() to access the message payload.