Search code examples
sessionexpressswig-template

Can i access sessions in ExpressJS without the request object?


I have an application that uses swig for templating, and sessions to store some client specific data.

I create my sessions inside a route like this:

exports.RenderIndex = function(req, res){
  if (req.body.filters) {
    var filters = req.body.filters;
    if (filters.date && filters.date.length > 0) {
      var d = moment(filters.date, "YYYY-MM-DD");
      var weekNumber = d.week();

      req.session.selectedDate = filters.date;
      req.session.selectedWeek = weekNumber;
    }
  }
};

Later on in my app i have a swig-filter needs to read and use my sessions, but i'm not quite sure how to access the sessions when i have no request object to take it from.

My swig-filter looks something like this:

swig.setFilter('getOpeninghourTable', function (input, idx) {
  var weeknumber = HERE_ID_LIKE_MY_SESSION_VALUE
  var data = calendar.json(input, weeknumber );
  return swig.renderFile(''template.html, calendarData);
});

IS it possible?


Solution

  • No, it's not possible. Why would it be? How would your code know what session to use?

    Any request-specific code must be in a request handler (or called from it) so it has a reference to the request data.