Passport.js: .authenticate() calls before initialize

I see this example for passport.js:

app.use(passport.initialize());

app.post(
  '/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
});

In most real apps, routers in other files handle the route handler definitions.

// router.js
import { Router } from 'express';

const router = Router();
router.post(
  '/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) { res.redirect('/'); }
);

export default router;

But now on the next step, updating the main server.js file, things are now out of order:

// server.js
import router from './router'; 
// passport.authenticate() was called before initialize() 

app
   .use(passport.initialize())
   .use(router); 

How do I solve this issue? Maybe a late import is needed – so, a require statement inside the app.use() to force it to import after the initialization step?

Or is there another/better way?

Hello!

That’s not an issue since you’re only defining (or configuring) the routes and middle ware, not really calling it (or accessing the routes).

If you were to start listening for connections before passport is initialized, that would become an issue.

1 Like