The Express Router is great! It is reliable and really simple. With Express 5.0 the router module was pulled out into a stand-alone package,
so I figured, why not see if it runs in the browser. Sure enough, it did! So this is a wrapper around the Express Router
package that layers on browser push state based location updates. I was heavily influenced by Page.js and use a
very similar method to transparently catch page changes events.
Unlike some other recent front-end routing attempts (**cough react-router, angular-ui-router and ember router cough**)1, this
package requires no special integration points into your links and no special methods to call to change routes. It layers transparently over your existing
application and catches link clicks which cause route changes.
It is also relatively small, weighing in at 19kb minified and gzipped. If you are using browserify you are probably already bundling modules like buffer
and process, so if you don't count those we only add 8kb total. This is a fair bit smaller than other comparable libraries for front-end routing. You
can see for yourself by running npm run disc, which will open a breakdown of where the file size comes from and display the minified and gzipped file size (File size: 8198 bytes gzipped).
NOTE: Requires HTML5 history api, aka pushState. This module does not support hash based routing.
Example:
var router = require('nighthawk')();// Register your routesrouter.get('/', function(req, res) { alert('Hi from your nighthawk router!');});router.get('/:foo', function(req, res) { alert('You visited /' + req.params.foo);});router.listen();
Setting A Base Path
Nighthawk supports service applications that are not hosted at the root of your domain via base. To set a base path just pass it in to
the router constructor. For example:
var Nighthawk = require('nighthawk');var router = new Nighthawk({ base: '/foo'});// Optionally you can also set the base path// with `router.base('/foo')`.router.get('/bar', function(req, res) { alert('You are not at /foo/bar');});router.listen();
What happens when history is not supported
It just falls back to basic HTML link behavior. Thats the great thing about this pattern, it builds on top of basic building blocks of the web. Also,
if it is not supported, your route will still run, so you can still use Nighthawk to kick off your application in unsupported browsers.
Run the examples
$ npm run example-basic$ npm run example-basedir$ npm run example-redirect
[1]: In opinionated frameworks this is not really that big of a deal because you are already tied down
to an ecosystem that probably works really well. But in a "pick your own adventure" style application it is much nicer to have less coupling.