Why would we nest routers in nested routers?


Why would we nest routers in nested routers?


Sometimes we have more than one level of complexity in our request paths, that is when nesting routers can come on handy, take a look at this route: /user/39576/dashboard/stats/2019
There we can see that our main route is handling a user endpoint which directs to a specific user (39576), to this point we are ok, but then we see that each of the specific users have a dashboard that has a stats path and it is furtherly separated by year. That is complex, and it might not be the most helpful thing to handle them in the same route handler, that is why separating the requests in smaller modules that we can nest it a plausible option.

Let’s take the expressions route of our app example and let’s imagine that our expressions are separated into face and body expressions, in that case our expressions route
will have to deal with queries that relate to facial emojis, like: :smiley: or :stuck_out_tongue_closed_eyes:.
and emojis with a body, like: :dancer:t2: or one of the faves: Person Facepalming on Apple iOS 12.1

This small dilemma will make our expressions route to juggle between two types of requests and their singularities.

so back to the example, we already have two routers, /animals and /expressions but now that we realize that our expressions route contains two types of expressions it would be smart for our sake to break it down into two more routers one for /expressions/facial y other for /expressions/physical.

We would see in our app that we are using two routers:

const expressionRouter = require('./expressionrouter.js');
const animalRouter = require('./animalrouter.js');

app.use('/expressions', expressionRouter);
app.use('/animals', animalRouter);

The same way we will work with our expressions router:

const expressionRouter = require('express').Router();

const faceExpressionsRouter = require('./faceemojis.js');
const bodyExpressionsRouter = require('./bodyemojis.js');

expressionsRouter.use('/facial', faceExpressionsRouter);
expressionRouter.use('/physical', bodyExpressionsRouter);

Now we can have all the requests passing from app to our expressions router and be directed to where they need to go, either facial or physical, and then be handled by the corresponding nested router.