9

i want to get cookie value in node server with socket.io

so every time socket send message to server i check the value of cookie

(i don't want session cookie) only in express i get the cookie by

 router.get('/', function(req, res, next) {

  var cookie_id = req.cookies.userIDf;
  console.log(cookie_id);
   res.render('index', { title: 'Express' });
});

its work here but with socket.io i cant get cookie any solution ?

io.sockets.on('connection', function (socket) {


var cookief =socket.handshake.headers['cookie'];
  console.log(cookief); // its give me session  id not the cookies
 });
2

1 Answer 1

17

You can use the cookie module to do this.

npm install --save cookie

var cookie = require("cookie") //installed from npm;

io.on('connection', function (socket) {
    
    var cookief = socket.handshake.headers.cookie; 
    var cookies = cookie.parse(socket.handshake.headers.cookie);    

});

cookief will return, but isn't accessible as a JSON object.

 io=5J1m_uXsDZvc61gTAAAA; userID=63kfh16tiu7md3ck7djv8856s0; userIDf=50

cookies, which parses cookief using cookie.parse(), will allow allow you to access each of the cookie values as a JSON object:

 cookies.io; //Returns 5J1m_uXsDZvc61gTAAAA
 cookies.userID; //Returns 63kfh16tiu7md3ck7djv8856s0
 cookies.userIDf; //Returns 50

or

 { io: 'RqIksBUQW4SM4zA4AAAA', userID: '63kfh16tiu7md3ck7djv8856s0', userIDf: '50' }
Sign up to request clarification or add additional context in comments.

2 Comments

Where does cookie.parse come from?
npmjs.com/package/cookie (for those wondering where cookie.parse comes from :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.