Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js client-sessions not creating req.session

Node.js client-sessions not creating req.session

Problem

I was having issues with node-client-sessions, so I tried using this sample application from https://github.com/fmarier/node-client-sessions-sample. However, even with this basic app I get TypeError: Cannot read property 'username' of undefined - req.session is undefined. Here's the code in full:

#!/usr/bin/env node

const
app = require('express')(),
clientSessions = require("client-sessions");

app.use(clientSessions({
  secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK' // CHANGE THIS!
}));

app.get('/', function (req, res){
  if (req.session.username) {
    res.send('Welcome ' + req.session.username + '! (logout)');
  } else {
    res.send('You need to login.');
  }
});

app.get('/login', function (req, res){
  req.session.username = 'JohnDoe';
  console.log(req.session.username + ' logged in.');
  res.redirect('/');
});

app.get('/logout', function (req, res) {
  req.session.reset();
  res.redirect('/');
});

app.listen(3000);

package.json has:

"dependencies": {
  "express": ">= 3",
  "client-sessions": ">= 0.0.9"
}

Whether I go to localhost:3000 or locahost:3000/login I get TypeError: Cannot read property 'username' of undefined

What's going on? Shouldn't node-client-sessions be creating req.session?

Problem courtesy of: tobek

Solution

Yeah as it turns out it's just that the default name of the req property changed from session to session_state. Changing that fixed it.

Solution courtesy of: tobek

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js client-sessions not creating req.session

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×