Sessions with node.js / Express – TypeError: Cannot set property ‘X’ of undefined

First off, to enable sessions in node.js with Express, add the following lines to the app config call:

app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));

And that will just do it – super easy.

If you run into a 500 error “Cannot set property X of undefined” it means you placed those two lines below app.use(app.router). It is important that app.use(app.router) is BELOW in your configuration function.

Also, to make sure your session variables are available in jade templates (including layout), use dynamic helpers included with Express:

app.dynamicHelpers({
  session: function(req, res){
    return req.session;
  }
});

In your jade template, simply call session variable like any other variable:

p#id My session var: #{session.var_name}
Advertisements

4 thoughts on “Sessions with node.js / Express – TypeError: Cannot set property ‘X’ of undefined

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s