Interceptors and per-connection state — WebSockets · NestJS

Run code around every message, and keep state for each connection: an interceptor that audits who sent what through the WebSocket execution context, and a request-scoped provider that Nest 12 creates once per connection, with that connection's socket injected.

What you will learn

Read the theory for Interceptors and per-connection state

All WebSockets lessons

All NestJS courses

loading types…

What you'll learn

  • Write an interceptor for a gateway that reads the socket, the payload and the event name through context.switchToWs()
  • Bind an interceptor to a gateway with @UseInterceptors(), and know it runs around each message, not around the connection
  • Keep per-connection state in a provider with scope: Scope.REQUEST, which Nest 12 creates for each connection, with the socket injected as REQUEST
  • Know that a gateway that injects such a provider becomes per-connection too