Search code examples
javascriptnode.jsexpresscookie-session

Conditional app.use in node - express


Is it possible to conditionally use app.use in app.js? Express cookie-session can not change the value of maxAge dynamically and I was thinking of doing something of this kind, but I'm getting some errors:

app.use(function(req,res,next ){
  if(typeof req.session == 'undefined' || req.session.staySignedIn === 'undefined'){
    //removing cookie at the end of the session
    cookieSession({
      httpOnly: true,
      secure: false,
      secureProxy: true,
      keys: ['key1', 'key2']
    });
  }else{
    //removing cookie after 30 days
    cookieSession({
      maxAge: 30*24*60*60*1000, //30 days
      httpOnly: true,
      secure: false,
      secureProxy: true,
      keys: ['key1', 'key2']
    });
  }
  next();
});

Instead of the normal use of it:

app.use(cookieSession({
  httpOnly: true,
  secure: false,
  secureProxy: true,
  keys: ['key1', 'key2']
}));

Right now I'm getting the following error:

Cannot read property 'user' of undefined

I believe it is referring to this line (although it doesn't say where exactly)

req.session.user;

Solution

  • A middleware in Express is a function such as function (req, res, next) {}. In your example, cookieSession(options) will return such a function, but in your middleware you don't run that, you disregard the return value of cookieSession - i.e. the middleware you want to run. Then you run next().

    What you want to do instead is to execute the actual middleware in your, let's call it, conditional middleware. Something like this:

    app.use(function (req, res, next) {
      var options = {
        httpOnly: true,
        secure: false,
        secureProxy: true,
        keys: ['key1', 'key2']
      };
    
      if(typeof req.session == 'undefined' || req.session.staySignedIn === 'undefined') {
        options.maxAge = 30*24*60*60*1000; // 30 days
      }
    
      return cookieSession(options)(req, res, next);
    });