2

I have an express app that was using redis cloud to store sessions in Heroku. It was working fine a few months ago, but I have just revisited it and it is no longer working. It seems there is no session, and throws the error TypeError: Cannot read property 'user' of undefined, the offending line of code is

if (!req.session.user) {
...
...
}

Maybe I'm configuring things incorrectly

var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require('redis-url').connect(config.redis_url);

var sessionMiddleware = session({
    store: new RedisStore({
        host: config.redis_host,
        port: config.redis_port
    }),
    secret: 'Its a secret.',
    cookie: { secure: true },
    saveUninitialized: true,
    resave: true
});

The corresponding config file is

module.exports = {
    mongo_url: process.env.MONGOLAB_URI || 'mongodb://127.0.0.1:27017/psa',
    redis_url: process.env.REDISCLOUD_URL || 'redis://localhost:6379',
    redis_host: taken from process.env.REDISCLOUD_URL,
    redis_port: taken from process.env.REDISCLOUD_URL,
    port: process.env.PORT || 5000
};

This works locally forman start web when I define the session middleware as follows

var sessionMiddleware = session({
    secret: 'VkWdLXauq6ya',
    saveUninitialized: true,
    resave: true,
    store: new RedisStore({
        client: redis
    }),
    cookie: {
        path: '/',
        maxAge: 3600000
    },
    name: 'sessionCookie'
});
Philip O'Brien
  • 4,146
  • 10
  • 46
  • 96

2 Answers2

1

Are you using the cookieParser middleware? You'll need:

app.use(express.cookieParser());

Seems like it is similar to this other stackoverflow question.

Community
  • 1
  • 1
stockholmux
  • 1,169
  • 11
  • 24
0

How are you using the created session middleware? eg:

var sessionMiddleware = session({

That creates a Function that can be used in your express stack. However, it does nothing until you actually use it, like:

var app = express();
app.use(sessionMiddleware);
hunterloftis
  • 13,386
  • 5
  • 48
  • 50