0.1.8 • Public • Published

    Project Router

    Build Status

    Promise based routing for Express apps. There are 2 parts to this library.

    1. A promises aware Route object you can extend
    2. A map function to connect routes and resources to Route objects


    Most request/response cycles of web apps follow the same pattern

    • run some code based on a URL
    • potentially reject or redirect based on authorization/authentication
    • create, read, update, delete data (aka CRUD)
    • present data back to the client

    I wanted to abstract the logic of mapping paths to files and have ways to hook into the request/response lifecycle as needed. Instead of having controller objects that manage a group of URLs I found it clearer (and easier to test) to have one object per URL (i.e. UsersShowRoute). If no route object exists it will render the corresponding view. If one does exists it will process the request by stepping through the lifecycle hooks. This lets you add logic to just one part of the request/response process.


    npm install --save project-router

    Basic Example


    var app = require('express')();
    var projectRouter = require('project-router');
    // Map paths to route objects
    // returns an instance of `express.Router()`
    var router = () {
      this.get('/', 'pages/index');


    var Route = require('project-router').Route;
    // Extend from the base `Route` object
    var PagesIndexRoute = Route.extend({
      // Define a model hook (this can return a value directly or a promise)
      model: function () { return User.findOne().exec(); }
    module.exports = PagesIndexRoute;


      The data return (or resolved) from the model hook is now available in the view.

    Seeing the routes

    Use Project Router Viewer to see a list of routes.

    Project Router Viewer Screenshot

    Extending the Route object

    Route objects are what handle incoming requests. There are a few request/response lifecycle hooks you can define. This pattern was heavily inspired by the Ember Router.

    Basic lifecycle hooks

    The following are the most useful lifecycle hooks listing in the order they are called. beforeModel, model, and afterModel can optionally return promises. These promises will be resolved before calling the next lifecycle method.

    The first method that gets called. This is your chance to do somehting synchronous (i.e. reject the request based on data already available).

    If you return a promise from this method it will be resolved before the model hook gets called. Useful if you have data you need to load asynchronously before getting the model'.

    Should return the data for the route or a promise that resolves to the data.

    Get passed the result of model. Use this for any logic that depends on having the data (like authorization that can only be determined with the object). This can also return a promise.

    Also gets passed the result of model. This just returns resolvedModel but can be used to transform the repsonse data (serializing, presenting, etc.)

    Catches any promise errors. Calls this.reject(reason) by default.


    .reject([code,] error)
    Ends request with error. Status code defaults to 400

    Delegates to Express response redirect method

    Delegates to Express response param method

    Renders this.templatePath with data as context

    Sends json response as data

    Returns this.request.params

    Returns this.request.body

    Returns this.request.query

    Properties available on route instance

    The Express request object

    The Express response object

    The path defined in router (i.e. '/users/:id')

    The view the route will render. Matches the route filepath by default. this.get('/users, users/index') will render app/views/users/index.hbs. You can define this property to change what template will be rendered (i.e. UsersIndexRoute.prototype.templatePath = 'pages/index;)

    The resource object (if defined). this.resource('users', {resource: UserModel}) would be UserModel. This can be defined on the router definition in the options hash or on the Route object (i.e. UsersIndexRoute.prototype.resource = UserModel).

    The name of the resource (if defined). this.resource('users') would be users.

    Example Route

    var Route = require('project-router').Route;
    module.exports = Route.extend({
      // Authorize request
      enter: function () {
        if (!this.request.isAdmin()) this.reject(401, 'Unauthorized');
      // Some special async admin authorization
      beforeModel: function () {
        return new RSVP.Promise(function(resolve, reject) {
          AdminAuth.canAccess('users', function (canAccess) {
            canAccess ? resolve() : reject ();
      // Get list of users (assuming this.resource is mongoose model)
      model: function () {
        return this.resource.findById(this.param('id')).exec();
      // 404 if model wasn't found
      afterModel: function (model) {
        if (!model) this.reject(404, 'Not found');
      // Namespace response
      responseData: function (model) {
        return { user: model.toJSON() };

    Defining routes

    Define routes by providing a map function to

    this.VERB(path, routeFile)

    Maps get, post, put, or delete to a route file. () {
      // Looks for `Route` object at 'app/routes/users/show.js'
      // and renders 'app/views/users/show.hbs'
      this.get('users/:id', 'users/show');
      // If no route is found at 'app/routes/pages/about' it will
      // create one and render 'app/views/pages/about.hbs'
      // Can be useful when there is no data that needs to be loaded
      this.get('pages/about', 'pages/about');

    this.resource(name, [options], [fn])

    Creates routes for a resource () {
      // Equivalent to
      //  this.get('/users', 'users/index');
      //  this.get('/users/:id', 'users/show');
      //  this.get('/users/new', 'users/new');
      //  this.get('/users/:id/edit', 'users/edit');
      //'/users', 'users/create');
      //  this.put('/users/:id', 'users/update');
      //  this.delete('/users/:id', 'users/destroy');
      // Control what routes are created with `only` or `except` options
      this.resource('users', {only: ['index', 'show']);
      this.resource('users', {except: ['desdtroy']);
      // Nest a resource by passing a function as the last argument
      // Will create paths in this format:
      //   '/users/:userId/posts/:postId/comments/:id'
      // And look for route file or view at
      //  'app/routes/users/posts/comments/show.js'
      //  'app/views/users/posts/comments/show.hbs'
      this.resource('users', function () {
        this.resource('posts', function () {
      // Use member and collection to add more actions to a resource
      // The following creates:
      //   '/users/:id/login'
      //   '/users/active'
      this.resource('users', function () {'/login');

    this.namespace(name, fn)

    Creates a namespaced scope for routes () {
      // Equivalent to
      // this.get('/api/users', 'api/users/index');
      // this.get('/api/posts', 'api/posts/index');
      this.namespace('api', function () {
        this.get('/users', 'users/index');
        this.resource('posts', {only: ['index']});




    npm i project-router

    DownloadsWeekly Downloads






    Last publish


    • moudy