The solution has two parts. First make the middleware function a static method of that class that you export from your module. This function needs to take an instance of your class and will invoke whatever methods you need to.
"use strict"; class Middle { constructor(message) { this._message = message; } static middleware(middle) { return function middleHandler(req, res, next) { // this code is invoked on every request to the app // start request processing and perhaps stop now. middle.onStart(req, res); // let the next middleware process the request next(); }; } // instance methods onStart(req, res) { console.log("Middleware was given this data on construction ", this._message); } } module.exports = Middle;
Then in your node JS / express app server, after requiring the module, create an instance of your class. Then pass this instance into the middleware function.
var Middle = require('./middle'); var middle = new Middle("Sample data for middle to use"); app.use(Middle.middleware(middle));
Now on every request your middle ware runs with access to the class data.
foo(req, res, next){ console.log('here'); }?