Last Updated: February 25, 2016
·
3.072K
· regality314

Skipping routes in express

The popular node.js framework, express, has a handy feature that isn't advertised, and can be extremely handy.

Suppose you have a page that you want to expire after a certain amount of time, and then say it's expired.Without this magical feature you might do something like this:

app.get('/will-expire',
  showPage,
  showExpiredPage
);

var hits = 0, maxhits = 10;
function showPage(req, res, next) {
  // this is mixing in logic that doesn't
  // belong here and isn't reusable
  ++hits;
  if (hits > maxhits) return next();

  res.end('not expired!');
}

function showExpiredPage(req, res, next) {
  res.end('page is expired :(');
}

We can make this code cleaner, reusable, and more modular by calling next with the string route. This tells express to stop running the callbacks for the matched route, and go try to match another route. Like this:

app.get('/will-expire',
  checkExpired,
  showPage
);

app.get('/will-expire',
  showExpiredPage
);

var hits = 0, maxhits = 10;
function checkExpired(req, res, next) {
  // next('route') will go to the next matched route
  // this is the magic we use to clean up our code
  ++hits;
  if (hits > maxhits) return next('route');
  next();
}

// showPage now is cleaner
function showPage(req, res, next) {
  res.end('not expired!');
}

function showExpiredPage(req, res, next) {
  res.end('page is expired :(');
}