Fizzix Fizzix - 1 year ago 81
Node.js Question

What is the best way to store global objects with NodeJS and ExpressJS

I'm trying to store data (most probably an object) so that it is accessible to my entire application. For example, info about my current logged in user (user ID and name).

I am wondering what the most efficient way is to do this in Node and Express?

After doing some research, I found a few ways, although most seemed quite unorthadox such as global objects (

global.myuser = {}

I also found that I could store an object as a module and include it where I need it, although I'm not too sure if data persists using this method.

What would be the best approach for this?

Answer Source

Have a module manage the data for you and then require() in that module anywhere you want access to it. require() is cached so subsequent calls to it get you back the same module every time which works well for shared data without actually using globally accessible variables which and while maintaining proper dependency management (globals are generally evil in node.js because they don't show dependencies at all).

Please be aware that globally accessible data in node.js is shared by requests from all users unless you specifically make it only available to some. So a variable like global.myuser sounds suspiciously dangerous unless the myuser is a server user (something there is only one of), not an actual user from a request.

Here's a simple example:

// shared_data.js
var myData = {someKey: 12345678};

module.exports = myData;

Then, in other modules:

 var sharedData = require('./shared_data.js');

 // you can access the sharedData object here

If you're trying to remember logged in users, then you need a more involved system that involves keeping track of a given user via a login cookie token and storing valid login tokens on the server that various requests can check to see if the user is actually logged in.

For logged in users with Express, I'd suggestion using express-session as it does 90% of the work for you. You get an object for each logged in user that you can store anything you want in and that info will be directly correlated to only that user.

The session object for the current user will automatically be available in the request object on any incoming request. And, you can pass that session object to any other function you wish to call from within a request.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download