nest: Middleware for socket.io not working

I’m submitting a…


[ ] Regression 
[X] Bug report
[X] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When I define a middleware like this:

import { Middleware, NestMiddleware, ExpressMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Middleware()
export class LoggerMiddleware implements NestMiddleware {
    resolve(...args: any[]): ExpressMiddleware {
        return (req: Request, res: Response, next: NextFunction): void => {
            console.log('Middleware got executed!');
            return next();
        };
    }
}

Then the console.log is never shown when I connect to my socket.io server from the client:

import * as socketIo from 'socket.io-client';
const manager: SocketIOClient.Manager = socketIo.Manager('/');
this.io = manager.socket('/asdf');
this.io.open();
this.io.emit('client_message', 'asdf');

Expected behavior

All middlewares are also executed when sockets connect & get emitted

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Not sure if it is intended like this or not. So I marked it as bug / feature

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 17 (3 by maintainers)

Most upvoted comments

You have the opportunity to use nest middleware for that purpose as the following example

@Middleware()
export class AuthenticationGatewayMiddleware implements GatewayMiddleware {
    constructor(private readonly userService: UserService) { }
    resolve() {
        return (socket, next) => {
            if (!socket.handshake.query.auth_token) {
                throw new WsException('Missing token.');
            }

            return jwt.verify(socket.handshake.query.auth_token, 'secret', async (err, payload) => {
                if (err) throw new WsException(err);

                const user = await this.userService.findOne({ where: { email: payload.email }});
                socket.handshake.user = user;
                return next();
            });
        }
    }
}

And then you can apply it in the gateway

@WebSocketGateway({
    middlewares: [AuthenticationGatewayMiddleware]
})

I hope that can help you if you are using nest under v5

In my opinion the token / cookie should only be passed when the connection between client & server is being established. So currently I just use a socket.io middleware with an custom implemented adapter that checks the value of the token / cookie.

If the token / cookie is not valid I call socket.disconnect(); -> So I know that I never have unauthenticated sockets to take care of.