Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
Socket.IO -- How can I fetch all connected sockets in a middleware in socket io?

I am using a middleware that validates JWT token from

socket.handshake.auth.token

After the token is validated I add the user in the socket variable like this

socket.user = user

I have a function that fetches all connected users using the io variable.

const getAllUsers = () => {
    const connectedSockets = Array.from(io.sockets.sockets.values());
    const connectedUsers = connectedSockets.map((socket) => socket.user);
    console.log(connectedUsers);
    return connectedUsers;
  };

But the problem is that I cannot access this io variable in my middleware. The middleware only has access to a socket and next variable. Is there a way I can access the io variable in my middleware. Or get all connected sockets in any other way?

PURPOSE:

I want to see if the same user is trying to connect with a different socket. And if he is, block the connection. Therefore I need array of all connected users.

Is there any other way to implement this logic without a middleware?

MIDDLEWARE

const protectSocket = async (socket, next) => {
  const token =
    socket.handshake.auth.token;
  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      //get user from token
      socket.user = await User.findById(decoded.id).select("-password");
      return next();
    } catch (err) {
      console.log(err);
      return next(new Error(err));
    }
  } else {
    return next(new Error("Token is missing"));
  }
about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!