title: Socket.io - Refresh tokens before reconnect
body: <p>I am creating an Electron app with Socket.io. When the user's computer goes into sleep mode the server disconnects from the client throwing an error "transport close". When the user tries to reconnect I check if the tokens are still valid, if they are not, I refresh them and try to send them to the socketIo server. </p>
  
  <p>The problem I have is that on "reconnect_attempt" socket.io doesn't wait until I refresh the tokens to try reconnecting, it tries reconnecting right away with the old tokens, which get rejected by the server, which also seems to terminate the connection with the user impeding future reconnect attempts.</p>
  
  <p>This is part of my code to connect to the server</p>
  
  <pre><code>module.exports.connect = async (JWT) =&gt; {
      return new Promise( async resolve =&gt; {
  
          console.log("connecting to the server")
  
          const connectionOptions = {
              secure: true,
              query: {token: JWT},
              reconnectionDelay: 4000
          }
  
          let socket = await socketIo.connect(`${process.env.SERVER_URL}:${process.env.SERVER_PORT}`, connectionOptions);
  
          resolve(socket)
      })
  }
  </code></pre>
  
  <p>This is my code for reconnect_attempt</p>
  
  <pre><code>socket.on('reconnect_attempt', async () =&gt; {
  
          const getCurrentJWT = require("../../main").getCurrentJWT;
  
          let JWT = await getCurrentJWT(); //By the time this line returns, socket.io has already tried to reconnect
  
          if(JWT.success) { //if refreshed successfully
              console.log("Trying to submit new token......", JWT);
  
              socket.query.token = JWT.JWT;
  
          } else {
              console.log("Token not refreshed.")
          }
      });
  </code></pre>
  
  <p>And this is part of what I have on the server</p>
  
  <pre><code>    io.use(async (socket, next) =&gt; {
  
    let token = socket.handshake.query.token;
  
    //and the instruction from here https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
    let tokenIsValid = await checkTokenValidity(token);
  
    if( tokenIsValid ) {
      next();
    } else {
      next(new Error('invalidToken'));
      console.log("Not valid token")
    }
  })
  </code></pre>