0

I am following a Node.JS tutorial that I saw the following code on it:

router.get('/checkJWTtoken', cors.corsWithOptions, (req, res) => {
  passport.authenticate('jwt', {session: false}, (err, user, info) => {
    if (err)
      return next(err);

    if (!user) {
      res.statusCode = 401;
      res.setHeader('Content-Type', 'application/json');
      return res.json({status: 'JWT invalid!', success: false, err: info});
    }
    else {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      return res.json({status: 'JWT valid!', success: true, user: user});

    }
  }) (req, res);
});

I can't understand why did it add (req, res) after the passport.authenticate() in both JavaScript syntax and also specifically authenticate() function?

Hasani
  • 3,543
  • 14
  • 65
  • 125
  • that's a callback function written in arrow function notation – Jaromanda X Feb 04 '20 at 07:50
  • 1
    Head to [the documentation](http://www.passportjs.org/docs/authenticate/) and scroll down to custom callbacks. `In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.` – Jeremy Thille Feb 04 '20 at 07:50
  • @JaromandaX the question is : why `passport.authenticate(...)(req,res)`? not about the callback function – Jeremy Thille Feb 04 '20 at 07:51
  • 1
    Then https://stackoverflow.com/questions/18234491/two-sets-of-parentheses-after-function-call is a duplicate – Quentin Feb 04 '20 at 07:53
  • oh, right, I got distracted by the completely incorrect first two so called "duplicates" - guess I'm not the only one who misread the problem - at least two other people voted this as a duplicate of something completely unrelated :p – Jaromanda X Feb 04 '20 at 08:12
  • 3
    FWIW you can remove that `(req,res)` at the bottom if you **also** remove the `(req,res) =>` at the top. Basically `authenticate()` returns a function that expects the regular arguments of routes/middlewares. So you are supposed to pass that returned function to the route directly. If you don't then you must call the return function yourself which is what the `(req,res)` at the bottom is doing - it is calling the return value of `authenticate()` – slebetman Feb 04 '20 at 08:42

0 Answers0