1

I'm setting request header while establishing connection to my Socket.IO server like this:

/* Socket.IO client */
let socketIO = new SocketIO("http://localhost:8080", {
  extraHeaders: {
    accessToken: "access123",
    refreshToken: "refresh123"
  }
});

How can I change the header after the client is connected (without disconnecting and reconnecting) ?

Tundra Fizz
  • 473
  • 3
  • 10
  • 25
saibbyweb
  • 2,864
  • 2
  • 27
  • 48

1 Answers1

3

Currently you cannot update the headers after the handshake. According to the documentation:

you can update the headers during a session, but it will not be reflected on the server-side (as the socket.handshake.headers object contains the headers that were sent during the Socket.IO handshake).

On the client side you can update the headers when changing the socket.io.opts.extraHeaders object, but if you wish the changes to be also reflected on the server you need to reconnect the client. On the client side you can force reconnection with something like client.disconnect().connect()

codtex
  • 6,128
  • 2
  • 17
  • 34
  • 1
    Alright, the only issue is my token is refreshed every minute. So disconnecting and reconnecting socket every minute, would that be stable? – saibbyweb Feb 04 '21 at 18:45
  • Well, this depends on how busy your application is and how powerful your servers are. I don't think that it is a good idea to use `extraHeaders` for storing authentication tokens, since you are going to refresh them so often. Check out the following post - [*"Authenticating socket io connections using JWT"*](https://stackoverflow.com/a/36821359/5452965). If you wish to implement something custom you can pass the tokens with every request as data parameters and have logic on the server to validate them and other channels which will refresh the tokens, its up to you. – codtex Feb 05 '21 at 13:37
  • I am authenticating with JWT only and came to the same conclusion of passing tokens as data parameters. But Is there any way to intercept the request and append the tokens for every event emitted (like interceptors in `axios`) or should I manually add the tokens to every event's data parameter. Like a middleware for client side? – saibbyweb Feb 05 '21 at 13:43
  • 1
    I am not sure that there is such a functionality integrated in `socket.io-client`, but you can always wrap the emitting in a function where you take care for always appending the tokens to the data which is send. – codtex Feb 05 '21 at 13:59