Gravatar of Jeroen Jeroen Pelgrims

Clean & efficient namespacing/routing in express 4

Posted on in node, express, coffeescript, software-development

A full example for both express 3 and 4 can be found on github.

I have a bunch of routes which are under the same namespace.
E.g.:

GET /api/person
POST /api/person
GET /api/person/:id
PUT /api/person/:id
DELETE /api/person/:id

I could start implementing these as follows:

app.get '/api/person', (req, res) ->
    #return people

app.get '/api/person/:id', (req, res) ->
    #etc.

But I have a problem.
I'm lazy, so fuck that shit.

Express 3§

In express 3 you had the express-namespace module which could alleviate your problems as follows:

express = require 'express'
require 'express-namespace' #Be sure to include this *before* creating your app object

app = express()

app.namespace '/api', ->
    app.get '/person', (req, res) ->
        #return people

    app.get '/person/:id', (req, res) ->
        #return person

   #etc.

Express 4§

In express 4 the Router class received a rework.

You can now do the following:

Router = (require 'express').Router

personRouter = Router()
personRouter.get '/', (req, res) ->
    #return people

personRouter.get '/:id', (req, res) ->
    #return person by id

apiRouter = Router()
apiRouter.use '/person', personRouter
app.use '/api', apiRouter

Looks more cluttered than the v3 example you say?
Well keep in mind that with this way you can more easily put everything in separate files without passing your app object everywhere.

Express 4 - shorthand§

In the previous example we've always attached a verb directly to a route, but you can also define a route on it's own and then attach verbs to that.

#app.coffee
express = require 'express'

app = express()

apiRouter = express.Router()
app.use '/api', apiRouter

apiRouter.use (require './person')
#person.coffee
Router = (require 'express').Router

peopleRouter = Router()

peopleRouter.route ''
    .get (req, res) ->
        #return people
    .post (req, res) ->
        #create person

peopleRouter.route '/:id'
    .get (req, res) ->
        #return person
    .put (req, res) ->
        #update person
    .delete (req, res) ->
        #delete person

module.exports = peopleRouter

This post is written by Jeroen Pelgrims, an independent software developer who runs Digicraft.eu.

Hire Jeroen