0

I am using Locomotive framework for creating a nodejs web-application.

In config/environments/all.js I have:


var express = require('express')
, poweredBy = require('connect-powered-by')
, util = require('util')
, connectAssets = require('connect-assets')
, redis = require('redis')
, RedisStore = require('connect-redis')(express)
, sessionStore = new RedisStore();

........
........

  this.use(express.cookieParser());
  this.use(express.bodyParser());
..........
..........
  this.use(express.session({
    secret: 'LoremIpsumDolorSit_Amet',
    store: sessionStore
  }));

However the session object is not present in the request object. ie. in a controller instance: this.req.session is undefined. What am I missing and How do I configure the connect-session middleware to use redis data-store ?

My redis server is running on default port and it shows a client connected when I run my server. The client gets disconnected only when I terminate the server.

I am using Node 0.6.18, redis server version 2.4.8, locomotive version 0.3.3 and express 3.0.4 on Fedora 16.

lorefnon
  • 12,875
  • 6
  • 61
  • 93

2 Answers2

0

For sessions to work in express, the three of the following must be in this very order:


this.use(express.cookieParser());
this.use(express.session(...));
this.use(this.router);

In my implementation, I had the third statement above the second.

Apparently, this is a known idiosyncrasy with Express and I am not informed enough about the inner workings of Express to explain why this is the case. Probably someone who has more experience with NodeJS can elaborate on the details.

lorefnon
  • 12,875
  • 6
  • 61
  • 93
0

With this.use(), you add middleware to Express' request/response handling: incoming requests pass through all middleware before ending up at your application, and outgoing responses go back up the middleware chain before being sent back to the client.

The order in which you install middleware matters: if you have one middleware (like express.session) which depends on another middleware (like express.cookieParser, to parse session cookies), you install the dependency first.

In most cases, this.router should be installed last, or almost last (usually followed by an error handling middleware), because it depends on cookies and sessions having been handled before it get called.

robertklep
  • 198,204
  • 35
  • 394
  • 381