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
 });
                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' }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With