Express next function, what is it really for?

next() with no arguments says "just kidding, I don't actual want to handle this". It goes back in and tries to find the next route that would match.

This is useful, say if you want to have some kind of page manager with url slugs, as well as lots of other things, but here's an example.

app.get('/:pageslug', function(req, res, next){
  var page = db.findPage(req.params.pageslug);
  if (page) {
    res.send(page.body);
  } else {
    next();
  }
});

app.get('/other_routes', function() {
  //...
});

That made up code should check a database for a page with a certain id slug. If it finds one render it! if it doesn't find one then ignore this route handler and check for other ones.

So next() with no arguments allows to pretend you didn't handle the route so that something else can pick it up instead.


Or a hit counter with app.all('*'). Which allows you to execute some shared setup code and then move on to other routes to do something more specific.

app.all('*', function(req, res, next){
  myHitCounter.count += 1;
  next();
});

app.get('/other_routes', function() {
  //...
});

In most frameworks you get a request and you want to return a response. Because of the async nature of Node.js you run into problems with nested call backs if you are doing non trivial stuff. To keep this from happening Connect.js (prior to v4.0, Express.js was a layer on top of connect.js) has something that is called middleware which is a function with 2, 3 or 4 parameters.

function (<err>, req, res, next) {}

Your Express.js app is a stack of these functions.

enter image description here

The router is special, it's middleware that lets you execute one or more middleware for a certain url. So it's a stack inside a stack.

So what does next do? Simple, it tells your app to run the next middleware. But what happens when you pass something to next? Express will abort the current stack and will run all the middleware that has 4 parameters.

function (err, req, res, next) {}

This middleware is used to process any errors. I like to do the following:

next({ type: 'database', error: 'datacenter blew up' });

With this error I would probably tell the user something went wrong and log the real error.

function (err, req, res, next) {
   if (err.type === 'database') {
     res.send('Something went wrong user');
     console.log(err.error);
   }
};

If you picture your Express.js application as a stack you probably will be able to fix a lot of weirdness yourself. For example when you add your Cookie middleware after you router it makes sense that your routes wont have cookies.

Docs

  • How do I setup an error handler?
  • Error Handling

You define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature (err, req, res, next):

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})