Filtering Backbone Routes

A Backbone application needs to perform a login redirect whenever an unauthenticated user tries to reach a restricted a page. It’s a trivial task over on the server-side, but the app is spread out across several controllers. It’s not the kind of situation that Backbone.Router will handle very gracefully by itself.

At one end of the spectrum, the application could use some kind of nifty pub/sub black magic to disable restricted routes when a user logs out. At the other, an appropriate test and redirect could be copied and pasted into teach of the offending routers. And somewhere in between overengineering and masochism is a third option—filtering the route directly. Get ready for a hack.

Here’s the skivvy. The navigate function used to handle Backbone routing can be easily replaced with an alternative version that runs route fragments through a Rails-esque filter before trying to pair them to a route:

// Monkey-patch Backbone.History
(function (History) {
  var _navigate = History.prototype.navigate;

  _.extend(History.prototype, {
filter: function (fragment) {
  // determine if fragment may pass
},
navigate: function (fragment, opts) {
  if (!this.filter(fragment)) {
    return _navigate.call(this, fragment, opts);
  }
}
  });
})(Backbone.History);

Now, route fragments will be passed through the filter method before being matched to a route. This creates an opportunity to do all kinds of things, from data injection to route rewriting. For example, a very simple filter will simply return true to block restricted routes from running:

// block access to /noop
filter: function (fragment) {
  if (fragment.match(/noop$/) {
console.log('operation not supported');
return true;
  }
}

It’s a hack, but there’s some undeniable utility here. Fiddle.

Hey, I'm RJ! For more learnings about software and management, find me @rjzaworski or sign up for my semi-regular newsletter.

Let’s keep in touch

Send me timely updates on software, product, and process.