tobek
tobek

Reputation: 4539

Node.js client-sessions not creating req.session

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 + '! (<a href="/logout">logout</a>)');
  } else {
    res.send('You need to <a href="/login">login</a>.');
  }
});

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?

Upvotes: 1

Views: 3477

Answers (1)

tobek
tobek

Reputation: 4539

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.

Upvotes: 2

Related Questions