Organization of Routes
You probably already know that it would be cumbersome and painstaking to define all the routes in the main application file. And not only would this file begin to grow over time, but it is also not a good way of separating functionality: there are already lots of things going on in that file. A simple site can have only a dozen or so routes, but a bigger site can have hundreds of routes.
Well, what do you do to organize the routes? More precisely, how would you like to organize them? How you do is not limited by Express web framework as it is not opinionated about it, but only by your imagination.
We will discuss some popular ways of handling routes in the following articles, but we generally recommend that you follow the three guiding principles for determining how to organize your routes.
- Apply named functions for route handlers
Our route handlers have been written inline by actually describing the function that handles the route here and now. This is suitable for small apps or prototyping, but as your site grows, it will quickly become too unwieldy.
- Routes should not look problematic
This principle is deliberately unclear, because a large and complex site may, as appropriate, require a more sophisticated organizational scheme than a ten-page e-commerce site. At one end of the diapason is just putting all the routes for your site in one single file so that you are aware of where they are situated. For larger sites, this may be undesired, so you will break the routes into functional areas. Nevertheless, even then it will become clear where to go to look for a particular route. When there is a necessity to fix anything, you will hardly want to spend an hour finding out where the route is being handled. We have an ASP.NET MVC project at work, which is simply nightmare in this regard: routes are handled in 10 different places at least, and it is not only inconsistent and illogical, but in many cases even contradictory. Despite the fact that we are well familiar with this site, that is very large, we still have to spend much time identifying where peculiar URLs are handled. We offer you to check how much load your ecommerce resource can take simultaneously. Stress testing service will help you analyze performance of your web to understand whether or not it can handle a wide audience.
- Do not ignore automatic route handlers based on views
If your site has many static pages and has fixed URLs, all your routes will end up appearing like that: app.get (‘/ static / thing’, function (req, res) {res.render (‘static / thing’). Needless code repetition can be reduced by using automatic view-based route handlers, an approach that can be used along with custom routes.