What is next() in express really for?


#1

Question

What is next() in express really for?

Answer

As we may remember from this lesson, next() is a middleware function that allows us to pass control to the next middleware function from the one we are in, which allows our application to keep running tasks if a response has been found or if there is an error it will prevent our server from crashing. For example:

app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id)
  next()
}, function (req, res, next) {
  res.send('User Info')
})

there anytime we get a request at users/:id it will go through the first middleware callback, console log the id and then using next() it will jump to the following callback that sends the string 'User Info'.

But that is not the only thing that next() can do. If you pass the error to next, it will move to the next error handling middleware and if you pass a route to it, it will run the function middleware for that route next. ie:

...
if (err) {
        next(new Error("No user found error: " + err));
        return;
      }
...