question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Middleware for socket.io not working

See original GitHub issue

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:

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:17 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
adrien2pcommented, May 12, 2018

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

1reaction
BorntraegerMarccommented, May 7, 2018

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Middleware(.use) does not emit connect when using a custom ...
To fix this i have to add .use((socket, next) => { next(); }) to default namespace. But still /admin does not emit 'connect'....
Read more >
Middlewares | Socket.IO
A middleware function is a function that gets executed for every incoming connection.
Read more >
Socket.IO middleware, io.use - Stack Overflow
io.use() allows you to specify a function that is called for every new, incoming socket.io connection. It can be used for a wide...
Read more >
10 - Authorizing Socket.io Connections In NestJS - YouTube
We'll ultimately apply a socket. io middleware to our customer NestJS "IOAdapter" to prevent sockets from connecting that do not not have a ......
Read more >
Socket.io - Feathers.js
Check out what's new, and please let us know about any issues or questions . ... Registering Socket.io middleware io.use(function (socket, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found