Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add headers to socketIO in flutter

I try to connect socket io in dart. I use socket_io_client: ^2.0.0-beta.4-nullsafety.0 for connection and use this code to connect:

Socket socket = io(
    '$server_address',
   OptionBuilder()
      .setTransports(['websocket'])
      .disableAutoConnect()
       .setExtraHeaders({'authorization': "$token"})
       .build());
socket.connect();

And it connects successfully. But, my headers (authorization) are not sent to the server. I also check my request and response with inspect of google chrome to make sure:

Screenshot

So, How can I send the headers with socket io?

like image 451
Marlen Schreiner Avatar asked Oct 20 '25 08:10

Marlen Schreiner


1 Answers

I think my answer is a bit late but it could help someone else. Anyway, I was facing the same issue and I found that socket_io_client in Flutter don't allow add extraHeader when you execute your app in the web (extraHeaders work fine in other platforms like Android or Windows), I think it is cause the securities restrictions of JavaScript when it's execute in a browser.

The solution that I found was use .setAuth({'authorization': "$token"}) instead of .setExtraHeaders({'authorization': "$token"}). Your code should be like this:

final socket = io.io( url.toString(), 
      OptionBuilder()
        .setTransports(['websocket']) 
        .disableAutoConnect()
        .setAuth({'authorization': "$token" })
        .build()
);
socket.connect();

In the server side, you can get your token using this: (This example is in NodeJS).

export const socketOnConnection = async ( socket : Socket, io : SocketServer ) => {
    const token = socket.handshake.auth[ 'authorization' ] ;  
    // ... rest of your code here
}

I hope it be helpfull.

like image 131
Juan Guerra Avatar answered Oct 23 '25 06:10

Juan Guerra