I would like some help understanding the following example from the passport.js authenticate documentation:
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next); //***UNSURE ABOUT THIS***
});
I understand what the code does - but I don't know what the (req, res, next)
at the end of the callback function is for. Why is it necessary? Does it provide the values for (err, user, info)
? If that's the case, why don't I see more function calls ending with arguments - Is it perhaps something to do with passing on the next
object?
Would love for someone to help me improve my understanding of this concept.
Request handlers are Express middleware; they get a request, a response, and a way to pass on execution to the next layer of middleware. passport.authenticate
returns middleware, but it hasn’t been attached with app.use()
, so you have to pass the appropriate arguments manually.
The fact that the callback from passport.authenticate
also has three arguments is just a coincidence. They won’t have the same values.