7

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js

function isAuthenticated (req, res, next) {
    // if user is authenticated in the session, call the next() to call the next request handler 
    // Passport adds this method to request object. A middleware is allowed to add properties to
    // request and response objects

    //allow all get request methods
    if(req.method === "GET"){
        return next();
    }
    if (req.isAuthenticated()){
        return next();
    }

    // if the user is not authenticated then redirect him to the login page
    return res.redirect('/#login');
};

Why does the author do return next() instead of next()? I know next() is to let the flow jump to next middleware or function, but why it needs a return for next() above?

Aleksandr M
  • 24,264
  • 12
  • 69
  • 143
Nichole A. Miler
  • 1,281
  • 2
  • 11
  • 21
  • So `isAuthenticated` returns whatever `next()` returns. This may not be a useful value, mind you. – Dave Newton Nov 10 '15 at 12:25
  • 2
    possible duplicate of http://stackoverflow.com/questions/16810449/when-to-use-next-and-return-next-in-node-js but it's valid and good question – Aishwat Singh Nov 10 '15 at 12:25
  • In the context of express middle-ware its to halt executing that specific piece of middle-ware should it fall into either of those if statements. Calling `next` tells express 'im done here move on' however without the `return` it could call `next` but then also try and perform a redirect. – ste2425 Nov 10 '15 at 12:39

1 Answers1

2

It's a convention to prepend a return to exit the function. The alternative would be to use if-else if-else instead of just if. In this case you just want to exit the function and step further on your middleware chain.

You'll see this pattern quite often. For example, this is pretty common:

someFunction(function(err, result) {
    if (err) {
        return console.error(err);
    }

    console.log(result);
});

It's less nesting and reads easier to most poeple compared to this:

someFunction(function(err, result) {
    if (err) {
        console.error(err);
    } else {
        console.log(result);
    }
});

The first pattern also keeps you from accidentally calling next() twice or even more times in case you have some error in your if-else-logic. And that's exactly what's not supposed to happen with next() in that case you posted. It could call next() and still cause the redirect in any case.

Num Lock
  • 742
  • 1
  • 6
  • 32
  • is this answering the question? I know what next() does but why return next(), that's my question – Nichole A. Miler Nov 10 '15 at 12:55
  • That's exactly what I am explaining in my answer, yes. It's just to exit the method at that point to avoid further calls. It's a pattern. It has nothing to do with `next()` really. It's mostly because the nature of _callback hell_. – Num Lock Nov 10 '15 at 12:57