Gateway Middlewares

Gateway middlewares works almost same as route middlewares. Middleware is a function, which is called before gateway message subscriber. Gateways middleware functions have access to native socket object. They can be something like a barrier - if middleware function does not call next(), the message will never be handled by subscriber.


export class AuthMiddleware implements GatewayMiddleware {
    public resolve(): (socket, next) => void {
        return (socket, next) => {

Some facts about gateway middlewares:

  • you should use @Middleware() annotation to tell Nest, that this class is a middleware,
  • you can use GatewayMiddleware interface, which forces on you to implement resolve() method,
  • middlewares (same as components) can inject dependencies through their constructor (dependencies have to be a part of module),
  • middlewares must have resolve() method, which must return another function (higher order function).

Okey, we already have prepared middleware, but we are not using it anywhere. Let's set it up:

    port: 2000,
    middlewares: [ ChatMiddleware ],
export class ChatGateway {}

As shown, @WebSocketGateway() accepts additional metadata property - middlewares, which is an array of middlewares. Those middlewares will be called before message handlers.

results matching ""

    No results matching ""