Search code examples
javascriptnode.jscookiesserver-side

Capturing Cookies (req.headers.cookie) on homepage with Express on node


I am doing a basic authentication example. I have Node, Express, and Cookie. I make and store a cookie once the user logs in. Upon refreshing the page, I want to use the cookie to show that the user is still logged in on the response, and provide the information related to that user.

Server side:

// If I put the app.get('/'.....) up here I get the response, but not the page HTML/JS/CSS/etc...

// This uses the /app as the root directory
app.use(express.static(__dirname + '/app'));

// Here I get the page HTML/JS/CSS/etc but can't capture the cookie
app.get('/', function(req, res) {
  console.log('I want to get here');
  if(req.headers.cookie){ 
    // This parses the cookies into a usable array
    var incoming_cookies = cookie.parse(req.headers.cookie);
    Person.find({...})
      .then( function(results) {
        if (weDontFindSomeone) {
          console.log('user not found');
          res.status(400).send('user not found');
        } else {
          if (incoming_cookies.uname === loggedIn.uname) {
            console.log('Starting with a cookie logged in');
            res.status(200).send(results);
          } else {
            console.log('Some other problem with cookies');
            res.status(400).send('Some other problem with cookies');
          }
        }
      })
      .catch(function(error){
         res.status(400).send('some other error in starting, error: ' + error);
      });
  } else {
    res.status(200).send('Starting from scratch.');
  }
});

How do I capture the cookies on the request to the homepage and use that to determine what is served to the client?

  • Do I put it in the JS on the client side?
  • If you want to suggest another node module, PLEASE show a working example in a plkr, fiddle, web page example, or the like. I do better studying working code, as it has taken me a bit long to get to this pont :)

Setting the cookie, also on the server side:

app.post('/api/login', function (req, res) {
  console.log('Getting a login request');
  if (weValidateTheCredentials) {
    Person.find({...})
      .then(function(personResults) {
        if (personResults.rowCount === 0) {
          res.status(400).send('user not found');
        } else {
          console.log('Logging in at \'/api/login\', and sending a cookie.');
          // 3 hours max age
          res.cookie('UID', req.body.uid, {maxAge: 10800000});
          res.cookie('uname', req.body.uname, {maxAge: 10800000});
          res.status(200).send(personResults);
        }
      })
      .catch(function(error){
          res.status(400).send('some other error in logging in, error: ' + error);
      });
  } else {
    res.status(400).send('login requires a uname and pwhash');
  }
});

Solution

  • I was mixing the paradigm of what should be handled by the server and what should be handled by the client.

    Using Jquery addon 'jquery-cookie-master', I can check the cookie on the request of the client side with if ($.cookie('attributeWanted')){...}