Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda