Daniele Margutti


A simple way to better handle routers in NodeJS and Express

Or… how to put OOP sauce in your functional backend

Node is my first choice when I need to make backend services for mobile or web applications. While JS is not my favourite language the overall approach to backend development is much more pleasant than using other tools like Java EE or PHP.
So, while I still waiting to see the official approach of Swift to server side development with the official Server APIs Group (hope to see something later this year, maybe WWDC?), I try to experiment different patterns while I’m still writing the backend services for a new side project.

In this short post I want to share with you a little pattern I use to better handling service routes.
The idea behind this pattern is to group each application context (authentication, user profile managment and any other specific application’s feature) in different classes which inherits from a base Router class.

This class exposes a construct which takes as input the Express application and the base path where services for the route are exposed; also this class ha a property called services where I’ll return the list of all services exposed by this specific route.

Let me show to you the base Router class:

It’s very simple; we simply declare the list of all services which needs to be exposed by a base route, then assign a function (in form of express route, so function route(req, res, next) {}) which needs to be called.

For example our Auth subclass maybe:

As you can see the path each route path is in the form:

  • VERB: is the HTTP method which expose the call (if not specified is GET, otherwise you should specify if it’s a POST,PUT etc.)
  • PATH: is the path of the service exposed (in the classic form of any Express request)

While the value is the name of the function you should to implement in your subclass.

At the end you can allocate and put in place your route as follows:

Each service exposed by our AuthRouter is available under the /users/auth path (ie, http://server_url/users/auth/login/fb/xxxx).

It’s very easy to implement and a good way to make order in your Node backend.

Topics of interest

More Related Stories