Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get socket.io option's query in nodejs

I created a chat application with android java as client and node.js as server side.

Client side:

IO.Options opt=new IO.Options();
opt.query="token=anything";
socket = IO.socket("http://xxx.xx.xxx.xxx:PORT",opt);
socket.connect(); 

i want to send a token on connection and get it in server for validation... how can i get the token that i pushed in opt.query in node.js?

And if you have good idea for sending some data like tokens on connection or somework for secure the connection Please note that.

Thank you

Solution server side:

io.on('connection',function(socket){
console.log(socket.handshake.query.token);
});

thanks for @Marcos

like image 848
ehsan mohajeri Avatar asked Feb 25 '26 19:02

ehsan mohajeri


1 Answers

You can access the query options in Node.js via socket.handshake.query

const ws = io(http);

ws.use(async(socket, next) => {

    try {
        await validateToken(socket.handshake.query.token));
        return next();
    } catch(e) {
        return next(new Error('Authentication error'));
    }

});

ws.on('connection', socket => {
      /* ... */
});
like image 93
Marcos Casagrande Avatar answered Feb 28 '26 08:02

Marcos Casagrande