Correct way of passing data from socket.io middleware to event

Viewed 1035

I want to pass some data from the socket.io middleware to the emitted event. I am extracting some details from the header token provided in the request and appending that extracted data to the socket object like this:

/* extracting details from token, before connecting */
io.use((socket, next) => {
    const details = fetchDetails(socket.request.headers.token);
    // appending details to socket object
    socket.details = details;
    next();
});

/* on connection event */
io.on("connection", (socket) => {
    console.log('Client conected');
    // accessing details fetched in the middleware
    console.log(socket.details);
});

Everything works fine, my only concern is whether this method is foolproof or not? Is it guaranteed that the data appended in the middleware will always accessible in the event, or can there be case in which my appended data will be over-written/lost in the event?

Is it the correct way to pass data from middleware to the emitted event?

1 Answers

Something like this should work EDIT: It's working fine even with typescript


    /* extracting details from token, before connecting */
    io.use((socket, next) => {
        const details = fetchDetails(socket.request.headers.token);
        // use socket.data to pass additional attachments
        socket.data = details;
        next();
    });


    /* on connection event */
    io.on("connection", (socket) => {
        console.log('Client conected');
        // accessing details fetched in the middleware from socket.data object
        console.log(socket.data);
        
        //If you want to pass another object in emit() from frontend
        socket.on("some_action", (anotherData) => {
          //Here's your data from event
          console.log(anotherData);
          
          //And here's your data from middleware
          console.log(socket.data);
        })
    });

Related