Sara Ree
Sara Ree

Reputation: 3543

How to use my own middleware with socket.io

I have a authorize middleware to allow the authorized user to go next, I use it like this:

router.post('/new-session-card', authorize(Role.Admin), newSessionCard);

So if the user is authorized he/she will go to newSessionCard function right ?

Now I want to use it with socket.io:

io.use(authorize(Role.Admin), () => {
        console.log('here')
});

The issue is the console log never reaches although the user is authorized .

Is there anyway to use my own middleware with socket,io ?

Upvotes: 0

Views: 223

Answers (1)

Sunil Thakur
Sunil Thakur

Reputation: 58

You can use function bind method in io.use() like this

In your case you can use it like

let Role = {
  Admin: "superuser"
};

function authorize(socket, next) {
   console.log("Role", this.role);
   next();
}

io.use(authorize.bind({role: Role.Admin}), () => {
        console.log('here')
});

Upvotes: 1

Related Questions