Skip to content Skip to sidebar Skip to footer

How To Make Module (such As Bcrypt) Available Globally In Express?

I have several 'routes' files where I import modules like this: var bcrypt = require('bcryptjs'); I have attempted to make bcrypt available globally by importing it into my main a

Solution 1:

app.use will only work with an Express middleware, which bcrypt is not, it's just a regular Node.js module.

As was pointed out in the comments, there is not really any reason why you shouldn't just use require to make bcrypt available in any module that needs it.

For what it's worth, you can use the globally available variable global to create a global variable in Node.js.

In your example, it would be used like this (but again, this is NOT RECOMMENDED):

var bcrypt = require('bcryptjs');
global.bcrypt = bcrypt;

Solution 2:

Though you've already accepted an answer, I thought I'd describe a lot more about why you don't want to use the global and why it's desirable to just require() in every module that you need.

The concept behind modules is that you should strive to make each module as independently usable as possible. In that spirit, there is no reason at all that you should make a module dependent upon a previous module initializing some global variable. That just makes one module depend upon the exact order of loading with some other module, ruins the ability to ever use that module independently and sets up a potential global variable naming conflict.

A big design goal of the module design in node.js is to avoid using globals. Instead, a module should either just require() in what it needs or it can be passed required data from other modules when it is loaded or it can query other modules for shared data by calling methods in those other modules.

In addition, loading a module with require() is cached. So, only the very first time a module is loaded with require() does it load from disk and execute. Every subsequent time it is loaded, the previously loaded module object is just immediately returned. Thus, it costs almost nothing to load a module more than once from various modules that need access to it.

So, every module that needs access to bcrypt should just do this:

const bcrypt = require('bcrytpjs');

Yes, this leads to repeating a few more things at the top of each module and that does sometimes feel a little less DRY than you might strive for generally, but it is overall a better tradeoff because it keeps modules as independent as possible as each module independently specifies what other modules it depends on and uses no globals to do that.


Post a Comment for "How To Make Module (such As Bcrypt) Available Globally In Express?"