Simplifying Route Declarations in Express

November 19, 2015

Organizing Routes in Node + Express If you’re in the same position as I was when I just started learning about Node.js & Express, you may have noticed that many intros or tutorials, although excellent introductions, will throw a lot of the code into the main app.js/server.js file.

An example route:

// Load Blog Posts View
app.get('/blog/:id?', function(req, res) {
  var id = req.params.id;
  if (id === undefined) {
    res.status(503);
    res.send('This page is under construction!')
  } else {
    var post = posts[id];
    res.send(post);
  }
});

Now imagine your entire app.js (or server.js) file filled with dozens of these types of routes, each with 10–15 lines of code (even more, if you’re making http requests)! That’s a lot of visual clutter.

Another way of presenting the same logic is:

var blog = require('./blog');
...
// Load Blog Posts View
app.get('/blog/:id?', blog.getPostById);

Concise, clean, and organized routes are the way to go, and will make you feel warm and fuzzy while you work instead of feeling anxious as you work on a behemoth of a file that you’ve created.

So how’s it done? Just take the anonymous function that you would regularly pass in the route declaration, and move it to another file. You will then export this function so that it is accessible by other files in your app, particularly, app.js (or server.js). Require the file and declare it as a variable, and then use object literal notation to call the function.

And that about wraps that!


Patrick El-Hage

I'm Patrick El-Hage and I live and work in San Francisco. I like to hang on Twitter.