Wrapping middleware as a function declaration

I have some middleware which is currently set up as a function that must get invoked in the route handler.

import auth from '../middleware/auth'

userRouter.get('/dashboard', auth().authenticate(), function(req, res) {
  res.send('It worked! User id is: ' + req.user.id)

This causes some problems with the order of execution when I import the route.

I would like to invoke it only when the route gets hit. Something like this (without the ())

import auth from '../middleware/auth'

userRouter.get('/dashboard', auth.authenticate, function(req, res) {
  res.send('It worked! User id is: ' + req.user.id)

How must I write the middleware in order to support this?


module.exports = function() {
  console.log('env, mongo', process.env.JWT_SECRET)
  var options = {};
  options.jwtFromRequest = ExtractJwt.fromAuthHeader()
  options.secretOrKey = 'superdupersecret'

  var strategy = new JwtStrategy(options, function(payload, done) {
    var user = payload._id || null;
    if (user) {
      return done(null, { id: user });
    } else {
      return done(new Error("User not found"), null);


  return {
    initialize: () => {
      return passport.initialize();
    authenticate: () => {
      return passport.authenticate("jwt", { session: false });

I suppose I must pass req, res, next to authenticate, but then how do I pass it to passport.authenticate?

Source: stackoverflow-javascript