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}

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

Leave a reply to Augustine Correa Cancel reply