0

I am using node.js and socket.io. on the client side, I wrote a cookie like this:

var socket = io.connect('http://localhost:3000');
document.cookie="foo=bar";
socket.emit('this', { is: 'test'});

and on the server side, I need to be able to read from that cookie inside a socket.io connection, something like this:

io.sockets.on('connection', function (socket) {
    socket.on('this', function(reqData){ 
        console.log(socket.handshake.headers); // there is no cookies here!
    });
}

a no-framework solution is preferred, any help is appreciated. thanks.

update: in this gist you can find my complete code.

Nasser Torabzade
  • 6,490
  • 8
  • 27
  • 36
  • 1
    Please see this question: [how-to-store-cookie-in-socket-io-socket-handshake-headers-cookie](http://stackoverflow.com/questions/19446602/how-to-store-cookie-in-socket-io-socket-handshake-headers-cookie/19451088#19451088) – Matthias Holdorf Oct 19 '13 at 08:15
  • @MatthiasHoldorf thanks for your help, but I've already seen that. some third party modules are involved, and some parts of answers are outdated. – Nasser Torabzade Oct 19 '13 at 08:50

1 Answers1

0

Try setting the cookie before making the connection from the client:

document.cookie = "foo=bar";
var socket = io.connect('http://localhost:3000');
socket.emit('this', { is: 'test'});

Here is a minimal example that I tested with. The server console.log's a new cookie with each reload of the page, as expected.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • @Nasser it does for me. Is your HTML being served by the same app? – robertklep Oct 19 '13 at 09:25
  • I think so! I have two separated functions in my app, one for serving files like this: `http.createServer(onRequest).listen(httpPort); function onRequest (request, response) { // stuff for serving files }` and another function for serving socket.io: `io.sockets.on('connection', function (socket) { // stuff for handling events }` and these two are called in my index.js , Do you think I need to change this architecture? – Nasser Torabzade Oct 19 '13 at 09:43
  • @Nasser `httpPort` is 3000? Does the code in my gist work for you? – robertklep Oct 19 '13 at 10:42
  • in my app, `socketPort` and `httpPort` are different. and no your gist didn't work for me. can you please check my code in [this gist](https://gist.github.com/nasser-torabzade/7054775)? thanks for your time. :) – Nasser Torabzade Oct 19 '13 at 11:36
  • @Nasser you took your gist offline again? gives a 404. – robertklep Oct 19 '13 at 12:15
  • no, github was down for maintenance(my bad luck!). it's ok now. – Nasser Torabzade Oct 19 '13 at 12:42
  • @Nasser I changed a code a bit to make it work, but the cookies seem to be sent just fine with your code too. – robertklep Oct 19 '13 at 13:07