174

I see a lot of use next in node.js.

What is it, where does it come from? What does it do? Can I use it client side?

Sorry it's used for example here: http://dailyjs.com/2010/12/06/node-tutorial-5/

look for the loadUser function.

2
  • I've not seen this anywhere, and it's not referenced anywhere in the documentation. Are you sure it's not defined somewhere in the code base you're looking at? Mar 21, 2011 at 22:38
  • That's far too vague. Can you give an example of context.
    – Raynos
    Mar 21, 2011 at 22:39

3 Answers 3

132

This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.

See, for example, the code samples here:

Let's look at the example you posted:

function loadUser(req, res, next) {
  if (req.session.user_id) {
    User.findById(req.session.user_id, function(user) {
      if (user) {
        req.currentUser = user;
        return next();
      } else {
        res.redirect('/sessions/new');
      }
    });
  } else {
    res.redirect('/sessions/new');
  }
}

app.get('/documents.:format?', loadUser, function(req, res) {
  // ...
});

The loadUser function expects a function in its third argument, which is bound to the name next. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser is done (unless a user could not be found).

There's nothing special about the name next in this example; we could have named it anything.

4
  • This is also used quite a lot in express.js but it's not .next(). He seems to ask about next as a method on an object.
    – Raynos
    Mar 21, 2011 at 22:44
  • 2
    Better to use return next(); Nov 16, 2016 at 21:40
  • 2
    @RyanWalton I agree
    – Wayne
    Nov 17, 2016 at 18:43
  • I used return callback() instead of return next()
    – vijay
    Jun 5, 2017 at 6:41
45

It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:

http://howtonode.org/control-flow

Also see the Sequential Actions section of the second part of that posting:

http://howtonode.org/control-flow-part-ii

4
  • 1
    Thanks a lot for this links. It explains a lot of things when start working with nodejs Apr 10, 2016 at 17:32
  • Link is not working now. It is giving Internal Server Error Jan 2, 2018 at 7:46
  • 1
    Updated links from internet archive
    – Pero P.
    Jan 8, 2018 at 6:04
  • thank you for the links, I started using Node a few months ago but I find myself using these practices but not fully understanding them
    – Amon
    May 28, 2019 at 16:48
11

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.