Socket.io-client: How to set request headers when connect to server?

Created on 9 Jul 2014  ·  13Comments  ·  Source: socketio/socket.io-client

how to set custom request headers when connect socket.io use js client

Feature request

Most helpful comment

@muhammadnasr Pass the options in the second argument, the first one being the url:

const socket = io("/your-url-here", {
  transportOptions: {
    polling: {
      extraHeaders: {
        'x-clientid': 'abc'
      }
    }
  }
});

All 13 comments

I also need that... Did you find any solution?

i am also interested in this.

I've seen how to do it on the Java socket.io-client but not the JS one

Won't Work with all transport-methods.
If you using XHR/Ajax Polling, it is possible, but not for WebSockets on HTML5.

http://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-apic

I'm searching for a solution to.

What are you trying to achieve? Can't you use url parameters?

I'm trying to write a test to verify whether websockets can be eavesdropped on before and after authentication middleware.

In order to successfully authenticate, however, I need to send a cookie session along with the initial http upgrade request. It works in the browser, I just want it to work in my node tests as well.

Is there any progress on this? Or any hint how to get/set the cookie-session / sessionId within socket.io?

I actually got it working. The details of the initial http handshake are available at socket.request. There, you'll find the session. For example, using the socket.io middleware:

io.use(function(socket, next){
    if (!socket.request.session){
      console.log('no session in socket')
      socket.disconnect();
    }
    next();
  });

Since version 2.0.0, you can now set request headers with the extraHeaders option:

const socket = io({
  transportOptions: {
    polling: {
      extraHeaders: {
        'x-clientid': 'abc'
      }
    }
  }
});

How can I add url to this example
const socket = io({
transportOptions: {
polling: {
extraHeaders: {
'x-clientid': 'abc'
}
}
}
});

@muhammadnasr Pass the options in the second argument, the first one being the url:

const socket = io("/your-url-here", {
  transportOptions: {
    polling: {
      extraHeaders: {
        'x-clientid': 'abc'
      }
    }
  }
});

That's great.

Do you have sample code to set headers for iOS and Android SDK?

Thanks a lot.

Can the headers be dynamically set?

Was this page helpful?
0 / 5 - 0 ratings