I am working with socket.io and I am struggling with sticky session. I have used cookie to achieve sticky session. Basically server return some cookie that should be send in next requests to get me to the same server and that is needed because I have multiple pods running on servers so I need to be sticked to same server every request because of handshake connecton I read the documentation: https://socket.io/how-to/deal-with-cookies#nodejs-client-and-cookies and I should resend that cookie by myself. I tried it and example in link is not working:
const COOKIE_NAME = 'sticky_cookie';
const socket = io('https://ws.example.com');
socket.io.on('open', () => {
socket.io.engine.transport.on('pollComplete', () => {
const request = socket.io.engine.transport.pollXhr.xhr;
const cookieHeader = request.getResponseHeader('set-cookie');
if (!cookieHeader) {
return;
}
cookieHeader.forEach((cookieString) => {
if (cookieString.includes(`${COOKIE_NAME}=`)) {
const cookie = parse(cookieString);
socket.io.opts.extraHeaders = {
Cookie: serialize(COOKIE_NAME, cookie[COOKIE_NAME]),
};
}
});
});
});
But I found out that it is working when I set cookie at the io creation as follow:
const socket = io('https://ws.example.com', {
extraHeaders: {
Cookie: 'sticky_cookie=123123123',
},
});
Is there a way to do that in a way to use socket.io meaning if I'm doing anything wrong. Or it's just a bug and I'll need to make some request before to get cookie? Thanks!