Search code examples
node.jscookieswebsocket

Reading cookie information from a WebSocket request


I'm using Node.js and WebSocket-Node (WebSocket-Node) to create a WebService. I need to access the cookie or session information from the web server to tie the WebSocket connection to a user id. I know that the cookie information is being send via req.cookies, but I'm not familiar with the syntax to access the "connect.sid" cookie.

Thanks!


Solution

  • By looking at the library code (around line 200):

    https://github.com/Worlize/WebSocket-Node/blob/master/lib/WebSocketRequest.js

    it seems that cookies is an array of object with "name" and "value" properties

    So you can have a function like this (not tested):

    function getSidFromCookies(cookies) {
         var filtered = cookies.filter(function(obj) {
             return obj.name == 'connect.sid';
         });
         return filtered.length > 0 ? filtered[0].value : null;
    }
    

    then you can just do:

    var connectSid = getSidFromCookies(req.cookies);
    

    connectSid will either be the cookie value or null