Elliot Elliot - 1 month ago 5
Node.js Question

Passportjs Callback, understanding arguments

I'm having trouble understanding whats going on with the custom callback for Passport.js. I don't understand the

(req, res, next)
at the end. Should we have these values from closure?

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); //<=== What is the purpose of this?


passport.authenticate() is a middleware. Briefly, a middleware is a function that modifies the request then passes it along to the next request handler. Request handlers in express are functions that take (req, res, next) as arguments. passport.authenticate, then, is a function which returns a middleware, which takes (req, res, next) as arguments.

Generally, it will be used like this:

app.get('/login', passport.authenticate());

whereby passport.authenticate() will modify the request, make sure the user is authenticated, then pass it along to the next handler.

In this case, we want passport.authenticate to do a little more, so we replace:

app.get('/login', passport.authenticate());

with the equivalent:

app.get('/login', function (req, res, next) {
  passport.authenticate()(req, res, next)

and then more logic is added into the passport.authenticate constructor.