6

I'm using Node.js along with express-session and I've got this session data that holds the user information

req.session.user

now when the user updates the information, I set the session to the new data and then reload it

req.session.reload(function(err) {
req.session.user = user;
});

it should work but the req.session.user still shows the old information, why? :(
many thanks in advance

Mohsen Shakiba
  • 1,762
  • 3
  • 22
  • 41

1 Answers1

15

You are reloading before saving your change. Saving usually happens at the end of the request automatically. There is a test in session.js which demonstrates that behaviour.

Using req.session.reload() reverts the changes that currently have been been made while processing the request ...

req.session.example = 'set on set_reload'
req.session.reload( function (err) {
    res.render('index', { title: req.session.example });
});
// next http get request
// req.session.example == value before the call above 

Consider using the session like this

req.session.example = 'set on set';
res.render('index', { title: req.session.example });
// next http get
// req.session.example == 'set on set'

If you have a real reason for using req.session.reload() then this type of usage will give you the desired behaviour

req.session.example = 'set on set_save_reload';
req.session.save( function(err) {
    req.session.reload( function (err) {
         res.render('index', { title: req.session.example });
    });
});
// next http get
// req.session.example == 'set on set_save_reload'
Christopher Hackett
  • 6,042
  • 2
  • 31
  • 41
  • thanks for the your answer but it still doesnt reload the session, let me explain it a little bit, I store the nickname of users in the session, but users can change the nickname, now when users change it, the session.user which holds the nickname has too change too but it doesn't so I need to manually reload it. – Mohsen Shakiba Feb 15 '15 at 15:10
  • 2
    Don't reload unless you wish to undo any unsaved changes to the users session. Just assign the new value and ``session`` will save the value. – Christopher Hackett Feb 15 '15 at 15:23
  • sorry for the delay and thanks for the help, I voted up as much as I could, It's the least I could do for your great answer – Mohsen Shakiba Feb 25 '15 at 19:33