Mohsen Shakiba
Mohsen Shakiba

Reputation: 1872

change and refresh session data in Node.js and express-session

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

Upvotes: 6

Views: 19730

Answers (1)

Christopher Hackett
Christopher Hackett

Reputation: 6192

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'

Upvotes: 16

Related Questions