Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Session MemoryStore in Express.js does not define req.session

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:

├─┬ [email protected]
│ ├─┬ [email protected]
│ │ └── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
like image 659
YMMD Avatar asked Apr 23 '12 21:04

YMMD


People also ask

How do I use session storage in node JS?

sessionStorage is a browser side API for storing values locally for the life of the browser session, that does not automatically get transmitted to the server. NodeJS is a framework and engine for creating server side applications. Perhaps you're needing the functionality of cookies. Show activity on this post.

Where is session data stored in express-session?

With express-session in particular, it has a built-in "not-meant-for-production" memory store (so session data is kept in memory and would not survive a server restart).

How do I handle multiple sessions in node JS?

Here, since sess is global, the session won't work for multiple users as the server will create the same session for all the users. This can be solved by using what is called a session store. We have to store every session in the store so that each one will belong to only a single user.


2 Answers

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.

like image 132
Linus Thiel Avatar answered Nov 15 '22 06:11

Linus Thiel


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.

like image 22
mihai Avatar answered Nov 15 '22 07:11

mihai