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?