Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS session variables won't stick

NodeJS session variables won't stick


I have a problem with nodejs and connect and the fact that it's not keeping the session variables between requests. For now I don't want to use a db to store my sessions. I just want to use the MemoryStore.

My server:

var server = connect()
.use(connect.session({ cookie: { maxAge: /* 1800000 */ }}))
.use(function(req, res, next) {, 404, true, {
        message: 'Call not supported'

I'm setting a session variable like this:

req.session.auth = true;
req.session.username = data.username;

After finding some more information about the issue I've noticed that it's probably to do with the time zone as it starts working if I just increase the timeout. From my past experiences using ASP.Net I've never encountered the issue before as it doesn't seem to care about that.

How can I get around this problem?

Problem courtesy of: Asken


Ok. So finally figured out how to do it. After reading a lot about how stupid I am for not running my server in UTC I decided to give it a try. I'm on ubuntu and here's the solution to get the cookies to work correctly.


sudo dpkg-reconfigure tzdata

Select "Etc" from the list of "Geographic areas" Select UTC and press Enter

UPDATE I noticed that my server time drifted quite heavily (virtual machine) so I also had to use a ntp-daemon to have it keep time properly. Setup is below:

sudo apt-get install ntp

You'll need to stop the ntp-daemon to be able to update it manually the first time. You can also reboot the server but it's Linux so you shouldn't have to. Run the below to stop the daemon:

sudo /etc/init.d/ntp stop

Update the server time manually (use a server close to you from


Just re-start the daemon again:

sudo /etc/init.d/ntp start

Also update the file /etc/ntp.conf and include your local time servers.

UPDATE AGAIN After running a day I noticed that the time is still off. I've now turned the UTC option off for the VM machine. This unfortunately also requires a reboot.

Solution courtesy of: Asken


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS session variables won't stick


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription