It’s not clear from the code fragments in your question where the problem, because I think you’ve omitted the place where you import the auth.route.js module.
The answer that follows assumes that you actually import auth.route.js in the index.js file, probably before importing middleware/auth (which isn’t actually used in the code fragment you posted). So, based on that assumption, here’s what’s probably happening:
The thing to keep in mind is that code in a module is executed when it is imported. This doesn’t affect middleware/auth at first, since all it does is declare a function. But it does affect auth.route.js – look at what that module does:
It imports the auth function from middleware/auth module, which calls the userRouter.get() function. One of the arguments to that function is a call to the auth() function.
If you’re importing auth.route.js in your code (and I suspect you are), then that’s where the auth function is getting called prematurely.
Now, how to fix this? It’s actually pretty easy: the auth.route.js file should export a function which is called to initialize the routes when you’re ready, like this:
auth.route.js
import auth from '../middleware/auth'
const userRouter = express.Router()
export default () => {
userRouter.get('/dashboard', auth().authenticate(), function(req, res) {
res.send('Authenticated, user id is: ' + req.user.id)
})
return userRouter;
}
And when you’re ready to initialize the routes (ie. when everything else is set up).
import getRouter from './modules/auth.route.js';
app.use('/api', getRouter());
1
solved Express.js app entry point