How to store or add data in socket object?

I have a socket id based on this I need to get user details. So can I store user details in the socket object?

How can I add user details in the socket object?

Here, I can store this socket id in Database but I need to update it every time when a user connects or disconnect. In this case, It’s effect the application performance.

I also implemented cluster mode here so I do not store these details in any global object.

Is this any way to store user detail in the socket object?

>Solution :

This Solution was helpful for me

io.on("connection", async (socket) => {
   socket.data = {
    userId: "",
  };

   const allSocketUsers = await io.in(roomId).fetchSockets();

   
  const postCreator = allSocketUsers?.find((userSocket) => {
    return userSocket.data.userId === id;
  });

   console.log(postCreator.id);
});

Leave a Reply