E
E
evlgromov2021-01-26 19:00:31
Socket.io
evlgromov, 2021-01-26 19:00:31

How to get web socket connection status in Vue component?

The socket connection is set up in index.js like this:

Vue.use(new VueSocketIO({
  debug: true,
  connection: SocketIO(process.env.BACKEND_URL, {query: `auth_token=${Vue.auth.token()}`}),
  vuex: {
    store,
    actionPrefix: 'SOCKET_',
    mutationPrefix: 'SOCKET_'
  },
}));

Next, in App.vue, we subscribe to the connect event using the Vue-Socket plugin and set the connection state flag:
sockets: {
    connect: function() {
      this.connect = true
    }
  },

Further, after authorization on the Login page, we redirect to the Home page, but the page is not rendered, because it does not pass the check for the state of the connected socket, which is set in App.vue and this.connect returns false until I reload the page:
<div id="app" v-if="appReady">
    <router-view />
</div>


appReady() {
      return this.authReady && this.connect
},


Perhaps the connection is established before authorization in the application and without a token it is not possible to establish a connection, but the server has the following settings:
io.use(jwtAuth.authenticate({
    secret: process.env.JWT_SECRET,
    algorithm: 'HS256',
    succeedWithoutToken: true
  },  async (payload, done) => {
    if(payload && payload._id) {
      try {
        const user = await (await User.findById(payload._id)).toObject();
        if(!user) return done(null, false, 'user does not exist');
        
        user._id = user._id.toString();
        done(null, user);
      } catch (error) {
        done(error);
      }
    } else {
      return done();
    }
  }));
  io.on('connection', (client) => {
    if (clients[client.request.user._id]) {
      return;
    }
    clients[client.request.user._id] = {
      clientId: client.id,
      role: client.request.user.role,
    };


How can I connect to the socket and set the connection flag when I authenticate?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question