How to Properly Setup and Use the Session In Node with Express

For the last couple of days I've been trying to setup a session in node. You know, so that I can access information as the user navigates from page to page. Typically this is so ridiculously easy to do with other stacks that you almost take it for granted.  The call backs to get and post requests have a req and res variable for request and response, respectively.  Typically you can access the session from the req in other stacks.  Not so in node.  At least not without the proper setup.

Say you have a module like below
exports.list = function(req, resp){

    //do something interesting here and call your view

}

Well in that module you can access the session member of the req like below:
exports.list = function(req, resp){
            req.session.userName = "foo";
            //do something interesting here and call your view
}

Then in some other function export you can use that session's property and use it for whatever.  If you are new to node this is can be the beginning of a few hours of digging and searching as to why all you get in your page is the error "Error 500 unable to set userName of undefine".  Well there are a few things that you must do.  First off you must set up your app to use express.cookieParser and express.session.  But that's not all. You must also make sure that you set these up before you setup any of your routes including the use of your router.  So basically your code should look like below:
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890'}));
app.use(app.router); //the router must be set up after the session
app.get('users', users.list); //routes must be after the cookie parser and the session

That's all it takes. Once you do that you should be able to use the session and use for whatever session variables you may need.

Here are a few links that may help you in case you have any further questions.

Comments

Popular posts from this blog

Simple Example of Using Pipes with C#

Difference Between Adapter and Bridge Design Patterns

Remote Access to Your Home Desktop Using No-IP