We are running a node.js app with express 4.6.1 cookie parser 1.3.2 connect-flash 0.1.1 and express session 1.7.0.
We use flash to display messages on pages after redirects and sometimes store data in the req.session to auto fill forms when the user makes a mistake and needs to reenter. Recently we started using pm2 in cluster mode and most things seem to work fine but we noticed that we lose our flash data and data stored in req.session after a redirect.
Here is an example:
req.flash("signup", errorString);
req.session.storedData = {};
req.session.storedData.username = "";
req.session.storedData.password = req.body.password;
req.session.storedData.email = req.body.email;
req.session.storedData.emailConfirm = req.body.emailConfirm;
res.redirect(problemRedirectPath);
This comes from an endpoint that accepts a request after the users tries to signup but has an error of some kind. If we run this in without cluster mode the session data and the flash both show up properly but if we run this in cluster mode, they are both almost always lost (be not always :/)
Is there a better way to do this in cluster mode?
Unless you use Redis, Memcache, some other process to store session data you will not be able to use more than one Node process to handle requests. Right now your app is only using express-session
to store session data, which by default only stores session data in memory.
https://github.com/expressjs/session#sessionoptions
See the warning section in the above link.
When you run an application with the cluster module it will fork a different process for each application instance. These processes cannot directly share memory without some work on your part to do so, which means when requests are round-robin distributed to the application instances any requests that do not end up at the same process will not be able to associate their cookie with the server-side session store.
I'd recommend changing your session store to something more production-ready such as Redis or Memcache. If you use Redis you may want to look at using connect-redis.