What is next() in NodeJs?

3245 views javascript

I am new to NodeJs coming from Java background, I'm trying to understand the use of the convention next() call.

I've gone through the following posts -
1. javascript node.js next()
2. https://www.naeemrana.com/node-js/express-js-middleware-what-is-next/
3. When to use next() and return next() in Node.js

What I could make of them is next() is similar to a callback or maybe a reference of the next function to be executed after the current function's execution,
Also understood it's recommended to use return next(); instead of next(); to avoid the function to be re-executed.

Following is a sample code from one the links -

app.get('/users/:id', function(req, res) {
    var user_id = req.params.id;

    if(user_id) {
      // do something
    } else {
      next(); // here comes middleware.

What I don't understand here is the function being executed does not have the 3rd argument,
but it does invoke the next() function, what is the idea here?
Is the use of this convention only to be used on routes logic?
Is next() a callback? is it a reference to the next function to be executed? or something else?

answered question

1 Answer


next() is not a nodejs thing but a express middleware function. Calling next() basically moves to the next middleware function. express is a web application for node.

You can read more https://expressjs.com/en/guide/using-middleware.html

Also, read through Express next function, what is it really for? which should you information.

posted this

Have an answer?


Please login first before posting an answer.