A few routes in a NodeJs app – no problem. Just put them in your
app.js. More than a handful? You’ll probably want to look at organizing your routes a different way. This will help keep your core
app.js clean and make your actual routes easier to find.
Did you know that Express comes with a binary/cli command called
express. This command will setup a project structure and a lot of the boilerplate code for you. The docs contain a guide on how to run this. It has support for other cool options like session support or various css preprocessors.
A sample run and the file structure that it will create looks something like this:
In that generated code, your
app.js references a route like this:
And the route,
index.js, looks like:
1 2 3
I like this, but it’s still not the best. I don’t like having to list the
app.get(), etc. in
app.js. This list will get long. So, how would I adjust?
All http commands in separate files
Instead, I want to tell
app.js about my routes, but I want each route file to hook itself up to express directly.
Showing the adjustments,
This time, more goodies in
1 2 3 4 5
The difference is somewhat slight. Now, instead of each http command listed in your app, only each resource (in REST terms) is listed in app. Each command for a resource is listed in that resource’s route.js.
There are surely many ways to organize your NodeJs routes. Express gives a great starting pattern. Our adjustment adds a slight optimization. Organizing your routes will help your main
app.js file stay way cleaner, and you’ll be able to find your routes more easily.
But this surely can’t be the best way for everyone. What are the ways that you’ve found successful in organizing your routes?
Note: this post uses express 3 syntax.