Prevent session from being created in Redis when authorization is not required

I have an api that uses Redis to store session state. This works great for the api routes that require authentication.

However, I have some routes that don't require authentication. When those routes are hit, a new session key is created in Redis (unless the user is already authenticated), but the value doesn't contain any useful information. I would like to prevent these useless entries from being created in Redis.

The trouble I'm having is the session gets created before my route handler is executed. So at the point the session is being created, I don't know if the route requires authentication or not.

  var sessionware = express.session({ ... session options ...});

  app.use(function session(req, res, next) {
    // if i knew i didn't need to save the session inside here, i could avoid doing so
    // but I have no good way of knowing that.
    sessionware(req, res, next);
  });

Am I missing something? This seems like it would be a fairly common scenario, but I can't find much about it anywhere.

There's at least a few ways to go about this:

  • You can write a middleware that only executes the session middleware depending on an attribute of the request (e.g. based on header values, cookies, request URL/path, etc).

  • A variant of the above where you have a custom middleware function that first checks for a session cookie and if it exists, it looks up that session key in redis. If it exists, call the session middleware.

  • Use the session middleware for individual routes. For example: app.post('/foo', session, function(req, res) {}).

  • Separate your unauthenticated routes by including them first and then use the session middleware and authenticated routes afterwards.