6

I have set up a Node.js test server with Express.js which looks like this:

var express     = require('express');
var MemoryStore = express.session.MemoryStore;
var app         = express.createServer();

app.configure(function() {
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(app.router);
    app.use(express.session({
        store: new MemoryStore(),
        secret: 'secret',
        key: 'bla'
    }));
});

app.get('/', function(req, res){
    console.log(req.session);
    res.end("html");
});

app.listen(3000);

Why does console.log(req.session) print out undefined? Didn't I use it correctly? What do I need to do in order to save variables to a user's session?

The client receives a SID which is stored as his cookie, but I cannot assign any attributes to req.session, because it is not defined. Thanks for any hints to solve this problem! :-)

This are the versions I'm using:

├─┬ express@2.5.9
│ ├─┬ connect@1.8.7
│ │ └── formidable@1.0.9
│ ├── mime@1.2.4
│ ├── mkdirp@0.3.0
│ └── qs@0.4.2
YMMD
  • 3,730
  • 2
  • 32
  • 43
  • what version of express are you using? – mihai Apr 23 '12 at 21:29
  • does it work without using MemoryStore? – Jonathan Ong Apr 23 '12 at 21:30
  • @mihai: Sorry for forgetting to mention the version - I have edited it into my posting now. @Jonathan: Leaving out the line `store: new MemoryStore(),` does not change anything. Sadly I don't have another session store which I could test if it works. – YMMD Apr 23 '12 at 21:34

2 Answers2

20

Here's your problem: app.use(app.router) mounts your routes in that position in the call chain. You have it before your session middleware, so there is no req.session yet. When you leave it out, your routes will be positioned whenever you do your first app.get (or app.post and so on). If you still wish to control where your routes should be, you can just move app.use(app.router) below the session middleware.

See Express' Configuration and Middleware documentation.

Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
  • You are right, after removing it everything worked as expected. Your answer is of course as good as mihai's, but I accepted his one, because he was first. Thank you very much for this awesome explanation!! :-) – YMMD Apr 23 '12 at 22:35
2

I don't know what app.router is but it seems to be the cause of the problem. Deleting that line made it work for me.

mihai
  • 37,072
  • 9
  • 60
  • 86
  • Well, I have no idea what kind of sorcery has put this line into my code. :D Thanks, removing it helps and my routes still work. – YMMD Apr 23 '12 at 22:33
  • 2
    From: http://stackoverflow.com/questions/10191692/session-is-undefined-when-using-express-redis-for-session-store It appears that use(app.router) before express.session breaks it.. having it after works. FYI :) – 0x6A75616E Jun 01 '12 at 04:51
  • 2
    @Linus G Thiel's answer below is more appropriate. – clayzermk1 Jan 17 '13 at 23:03