How to send custom data along with handshake data in socket.io?

Sometimes, we want to send custom data along with handshake data in socket.io.

In this article, we’ll look at how to send custom data along with handshake data in socket.io.

How to send custom data along with handshake data in socket.io?

To send custom data along with handshake data in socket.io, we can call io with an object with the custom data we want to send as the 2nd argument on client side.

For instance, on client side, we write

const socket = io("http://127.0.0.1:3000/", {
  query: "foo=bar"
});

to call io to create the connection.

Then on server side, we write

io.use((socket, next) => {
  console.log(socket.handshake.query);
  if (socket.handshake.query.foo === "bar") {
    return next();
  }
  next(new Error('Authentication error'));
});

to call io.use with a callback to listen for handshakes.

And we get the value of the query property of the object we called io with on client side with socket.handshake.query.

Conclusion

To send custom data along with handshake data in socket.io, we can call io with an object with the custom data we want to send as the 2nd argument on client side.