In this post I will show how I simplified the routing structure of my blog application.
My blog is a custom Node/Express application, built from scratch. In addition to articles I often publish supporting code samples hosted from my server.
Well, I’ve been blogging for a while now, and the routing to my code samples is starting to spiral out of control.
I started out with just a few routes following a completely flat routing structure in my server.js file. The biggest downside to this is that my server.js is much bigger than I would like it to be.
To get better route organization I have decided to add Express Router to “modularize” my routes.
Here is an example of the old structure in server.js:
It’s basically just a long list of routes…
Now, how can this be ported over to Express Router?
Luckily this is really easy!
All you have to do is move the routes to a separate file and tweak the definition very slightly. In my case I moved the routes to a file called build.js under a “routes” folder. The folder or file name is not important here though.
Now in the main server.js file I can require the route definitions like so: