Express next function, what is it really for?


Have been trying to find a good description of what the next() method does. In the Express documentation it says that next('route') can be used to jump to that route and skip all routes in between, but sometimes next is called without arguments. Anybody knows of a good tutorial etc that describes the next function?

9/8/2017 6:13:17 PM

Accepted Answer

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) {
  } else {

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;

app.get('/other_routes', function() {
10/30/2012 5:33:51 AM

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');

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow