Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda