How to dynamically set auth in handshake in Socket.IO client?

Viewed 183

On the frontend/client-side, I have an implementation where I secure my socket.io connection using auth token. This auth token is updated in the store every few minutes.

const authToken = getToken()
socket = io(WS_BASE_URL, {
    auth: {
        token: authToken
    }
});

In this current implementation, when the socket tries to reconnect, authToken is not updated. How to dynamically set it every time reconnect attempt is made?

socket = io(WS_BASE_URL, {
    auth: {
        token: () => getToken()
    }
});

I want this kind of implementation where I pass a function to get the token every time from the store. Or is there any way we can modify handshake data in the reconnect_attempt event?

socket.io.on("reconnect_attempt", () => {
    // update handshake
});
1 Answers

socket.io 2.x client api document has this

"The query content can also be updated on reconnection:"

socket.on('reconnect_attempt', () => {
  socket.io.opts.query = {
    token: 'fgh'
  }
});

I think you use 4.x because you use auth option, but I think it is basically the same. The middleware at server side will get the update token when a socket reconnect.

Related