Where should i store current user in node.js?

As with almost any web application, I need a way to reference the current user in my node.js app.

I have the login/session system working, but I noticed today that when I login to my app in one browser, and view it in another, I can see the same data that I see in the first browser.

I am currently storing the information about the current user in a global app.current_user object, but I realize now that this is shared across all requests/sessions because node.js is single-threaded - and therefore, is a bad idea.

What would be the correct way to store the reference to the current user? The current user is not just a hash of user data, but a Mongoose model, so I guess storing in a cookie would not be a good idea?

BTW - I also store the user's settings and a few more things that I do not want to fetch again each time I do something with the user and their settings (which can happen quite a few times during a single request). I guess you could say I'm caching the current user in memory.

It seems the correct place to store information about the current user at the moment is in the request object.

If you do not like the idea of passing the request object to mongoose or other modules, then you need to make any changes in your router/controller/middleware. For example, I can set the lastModifiedBy user ID for the Post model in my posts_controller update() action.

You can also try using the fairly new domain feature to store current user data, but when working with Mongoose, it doesn't help yet, because Mongoose does not support domains yet: https://github.com/LearnBoost/mongoose/pull/1337

In express you can use session

//To set up session 
app.use(express.cookieParser());
app.use(express.session({secret: 'secret pass', store: sessionStore})); 
//To use it
req.session = {user:name , model:mongo_model};
console.log(req.session.user);

Examples

  1. See a simple example here
  2. See how to use mongostore for session data in this question