DEV Community

loading...
Cover image for ExpressJs Route Management

ExpressJs Route Management

Chiemeke Ifeanyi
・2 min read

ExpressJs is an un-opionated framework for building NodeJs application quick. It comes with a routing feature which is quite easy to implement. But if you have written multiple ExpressJs powered project, you would agree with me that your routes becomes messier and even very hard to maintain as it begins to grow.
To solve this problem, I use a ExpressJs Route Manager to manage this ever growing routes.
Using Expressjs Route Manager your routes can be easily managed.

Here is an implementation:

server.js

 const express               = require("express");
 const app                   = express();
 const options               = {
                                 routeFile:"app/routes",//path to your route file
                                 controllerDirectory:"app/controllers",//path to your controller files 
                                 middlewareDirectory:"app/middlewares" //path to your middleware files
                               }
 const expressRouterManager  = require("expressjs-route-manager")
(app,options);


 app.listen(process.env.API_PORT||'3000',(err)=>{
      console.log(`> server started on port ${process.env.API_PORT||'3000'} `
 });

 app.on('error',(err)=>{
      console.log(err);
      return;
 })

app/routes.js
Let's assume that our application has an api namespace which in turn has an auth namespace which has a login endpoint, our route file would thus look like this:

module.exports = {
    'api': {
      'auth': {
         'login': {
            controller: {
               path: 'auth',
               method: 'login'
             },
             verb: 'post'
           }     
        }
    }
}

controller
Writing your controller is the same as always. Here is an example:

app/controllers/auth.js

 module.exports = class Auth{
                    login(req,res){
                      res.send('hello world');
                    }
                  }

There are numerous ways of writing your controller, you are not limited to the example above. For example you could write it as a function.
Lets add a signup controller to our application.

module.exports = {
    'api': {
      'auth': {
         'login': {
            controller: {
               path: 'auth',
               method: 'login'
             },
             verb: 'post'
          },
          'signup': {
            controller: {
               path: 'signup',
             },
             verb: 'post'
          }   
        }
    }
}

app/controllers/signup.js

 module.exports = (req,res)=>{
                   res.send('hello world');
                  }

Note: When using functions as your controller, you do not need to add method property to your controller, if you do so ExpressJs Route Manager would treat your controller as a class instead of a function.

The above routes would be accessed via:
/api/auth/login
/api/auth/signup

NameSpace

ExpressJs Route Manager helps you group your routes within namespaces. For instance, the above examples shows that the api namespace houses the auth namespace. The end of a namespace is indicated by the introductionn of a controller.

Middlewares

Middlewares can be added at any point in your route namespace. When a middleware is added within a namespace, it affects that namespace and even its children namespaces.
We are going to modify our route file to use middlewares.

module.exports = {
    'api': {
      middlewares:["cors"],
      'auth': {
         'login': {
            controller: {
               path: 'auth',
               method: 'login'
             },
             verb: 'post'
          },
          'signup': {
            controller: {
               path: 'signup',
             },
             verb: 'post'
          }   
        }
    }
}

app/middlewares/cors.js

module.exports = function cors(){
  return function (req,res,next) {
    //do middleware things here
    next();
  }
}

You can add middlewares at any level of your route file.

Conclusion

Managing your ExpressJs routes can be a pain in the ass most times and this simple library objects to build your routes intuitively and with simplicity.

Have an idea on how to make it even better? Create a pull request here:

GitHub logo darnyelx / expressjs-route-manager

A library that helps you organize and group your expressjs route intuitively

NPM package can be found here:

Discussion (0)