Setting session variables in sailsjs

Recently, I lost about 2 hours trying to set a session variable in my sailsjs application and which was not working. In fact, this was a very straight forward action: set the session variable and use it elsewhere.

What I got wrong was the following: if you want to set your session variables, you need to set it before your redirection or before your render your views.

For example, the following will not work:

User.update({id: userId}, {details: details_data}).exec(function(err, updated)
{

req.session.user = updated;

});

res.redirect(”/login”);

simply because the req.session.user = updated line is executed asynchronously and will not take effect. To make this work, you simply need to set the session variable outside the asynchronous function like this:

User.update({id: userId}, {details: details_data}).exec(function(err, updated)
{

//do some stuff here

});

req.session.user = updated;

res.redirect(”/login”);

 

Facebook Comments

Oct, 10, 2016

  JS

0

SHARE THIS