What is the proper way to require a module for use in httpNodeMiddleware?

I have the this declaration in my httpNodeMiddleware function:

var jwt = require('jsonwebtoken');

Where can I move this too so that I don't have to load the module every time a request comes in?

cheers,

In settings.js file

https://nodered.org/docs/user-guide/writing-functions#loading-additional-modules

You don't really need to worry too much about that actually since require won't reload the module. That's one of the nice features. You can load the same module in lots of places within a node.js app and it will only ever load it once.

That's how the singleton class module approach works.

Hi Steve,
Thanks for your reply, but I believe that only works for functions created in your flow, not for functions in the settings.js file itself.

Thanks for your reply that is really good to know.

After sleeping on it I came up with two answers to my own problem :slight_smile:

  1. If all you need is some variables that will be persist between function calls then you can use the module pattern:
httpNodeMiddleware: (function(){
    var jwt = require('jsonwebtoken');
    return function(req,res,next) {
        //jwt object is accessible from here and is not reinitialized every time the function is called.
    };
})(()
  1. However if you need variables that can be accessed from and of the middleware function in settings.js then the answer is really simple: Just declare them at the top of setting.js! I didn't think of this last night as I was thinking of the settings as a json file that the function was copied out of. But setting.js is just a file that is included and called directly, so you can just add objects directly to it.

One word of caution, if you can get way with using the module pattern then it is the much safer approach, as any variables you add are only accessible within your module. If you use the second approach and modify settings.js directly then this could cause issues in the future if the Node-Red developers add a property to settings.js that you've already used for something else.

cheers

1 Like