Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

Express Router

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Sat Jul 15 2017

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:

old server.js
app.get('/build1', function(req, res){ res.render('build1.html'); }); app.get('/build2', function(req, res){ res.render('build2.html'); }); app.get('/build3', function(req, res){ res.render('build3.html'); }); app.get('/build4', function(req, res){ res.render('build4.html'); }); app.get('/build5', function(req, res){ res.render('build5.html'); });

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.

I also migrated the syntax to ES2015 JavaScript, but this is an optional enhancement.

routes/build.js
const express = require('express'); const router = express.Router(); router.get('/build1', (req, res) => { res.render('build1.html'); }); router.get('/build2', (req, res) => { res.render('build2.html'); }); router.get('/build3', (req, res) => { res.render('build3.html'); }); router.get('/build4', (req, res) => { res.render('build4.html'); }); router.get('/build5', (req, res) => { res.render('build5.html'); }); module.exports = router;

Now in the main server.js file I can require the route definitions like so:

const buildRoutes = require('./routes/builds'); app.use('/', buildRoutes);

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter