I tested out the solution you gave @Marc and this causes a memory leak if you use a session store like Mongodb, because a new connection to it is created each time the app receives a request.
The error:
(node:4333) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 disconnect listeners added to [MongoStore]. Use emitter.setMaxListeners() to increase limit
(node:4333) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connect listeners added to [MongoStore]. Use emitter.setMaxListeners() to increase limit
To fix that, you might want to memoize the middleware function returned after the first go so you only have one listener on the store:
let memo = {middle: null};
app.use((req, res, next) => {
// do here what you want with req,res,next
let middleware;
if(memo.middle){
// call if it already exists
middleware = memo.middle;
} else {
middleware = session({
"name": "session",
"secret": "null",
"resave": false,
"saveUninitialized": true,
"store": mongoStore,
});
// store instance we get otherwise.
memo.middle = middleware;
}
// call middleware function
middleware(req, res, next);
});
This reflects the same behaviour as passing the middleware via app.use(session(config)), which is the goal of the last part of the middleware. Just like subsequent requests passing through app.use(session(config)) will reuse the same middleware and not call session(config) again, subsequent calls on this middleware would use the initial value of middleware returned from session(config) as memoised.
Error handling is up to you to ensure a good UX.