Kest

Search

Search the documentation

WebSockets

Pipes

Validate and convert the data of a message.

A pipe works on the payload of a message before your handler sees it, as it does for an HTTP body. Use ValidationPipe so a bad message is refused with a clear error and your handler only receives valid data.

data class ChatMessage(@field:NotBlank val room: String, @field:Size(min = 1, max = 500) val text: String)
 
@WebSocketGateway("/chat")
class ChatGateway {
    @SubscribeMessage("say")
    fun say(client: WsClient, @UsePipes(ValidationPipe::class) msg: ChatMessage) { ... }      // ChatMessage carries @NotBlank etc.
}

A client that sends {"event":"say","data":{"room":"","text":""}} receives:

{ "event": "exception", "data": { "status": 400, "message": "..." } }

and the handler does not run. Pipes can also be attached to the whole gateway (@UsePipes on the class) or globally (useWebSockets { ... } pipeline configuration).

Notes

  • The pipe sees the message payload as a BODY argument, with its name and type, so your own Pipe (trim, normalise) works the same as for HTTP.
  • Always validate: a WebSocket is open to any client, and a handler that trusts its input is a vulnerability.
  • Limit message size at the server (the engine's frame limits) as well as validating fields.

Read more