Linux
Linux

Reputation: 343

Why do we use next() function?

Do we use it only in middlewares or the functions with no routes? I have used it in my authentication file...

function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
    return next();
  } else {
    req.flash('error_msg' , 'Please login First...')
    res.redirect('/users/login');
  }
}

Upvotes: 3

Views: 589

Answers (2)

Damaged Organic
Damaged Organic

Reputation: 8467

If you talking about Express framework here - next function is just a callback telling that this particular middleware handler should execute next operation in Express middleware chain.

If you define any handler with signature someHandler(req, res, next) and register it with app.use, it will become a part of that chain. Essentially it just a special callback function - disregarding the purpose of the function itself - route controller, authentication, body parser, etc.

Upvotes: 3

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5694

You execute it in order to execute the next middleware in the pipe. If you don't execute it manually, you're probably passing it on to a different module that executes it for you. Otherwise, if you don't execute next, you cut the "pipe" short i.e. yours is the last middleware that runs.

In your case it makes perfect sense to call next() when the user is authenticated. That passes the control to the next piece of middleware. It also makes sense not to call next() in the case that you've already established that the user is not authenticated, since in most cases you don't want the rest of the middleware in the "pipe" to execute.

So yes, next() is used by middleware, or modules intended to be called by middleware.

I hope that answers your question.

Upvotes: 3

Related Questions