Node.js / Express.js - How does app.router work?

Routing means determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Each route can have one or more handler functions, which are executed when the route is matched.

In Express 4.0 Router, we are given more flexibility than ever before in defining our routes.

express.Router() is use multiple times to define groups of routes.

route used as middleware to process requests.

route used as middleware to validate parameters using ".param()".

app.route() used as a shortcut to the Router to define multiple requests on a route

when we are using app.route(), we are attaching our app with that router.

var express = require('express'); //used as middleware
var app = express(); //instance of express.
app.use(app.router);
app.use(express.static(__dirname + '/public')); //All Static like [css,js,images] files are coming from public folder
app.set('views',__dirname + '/views'); //To set Views
app.set('view engine', 'ejs'); //sets View-Engine as ejs
app.engine('html', require('ejs').renderFile); //actually rendering HTML files through EJS. 
app.get('/', function (req, res) {
  res.render('index');  
})
app.get('/test', function (req, res) {
  res.send('test')
})

In express Version 4 we can easily define routes in the following manner:

server.js:

const express = require('express');
const app = express();
const route = require('./route');

app.use('/route', route);
// here we pass in the imported route object

app.listen(3000, () => console.log('Example app listening on port 3000!'));

route.js:

const express = require('express');
const router = express.Router();

router.get('/specialRoute', function (req, res, next) {
     // route is now http://localhost:3000/route/specialRoute
});

router.get('/', function (req, res, next) {
    // route is now http://localhost:3000/route
});

module.exports = router;

In server.js we imported the router object of the route.js file and apply it in the following manner in server.js:

app.use('/route', route);

Now all of the routes in the route.js have the following base URL:

http://localhost:3000/route

Why this approach:

The main advantage of taking this approach is that now our app is more modular. All the route handlers for a certain route now can be put into different files which makes everything more maintainable and easier to find.


Note: This describes how Express worked in versions 2 and 3. See the end of this post for information about Express 4.


static simply serves files (static resources) from disk. You give it a path (sometimes called the mount point), and it serves the files in that folder.

For example, express.static('/var/www') would serve the files in that folder. So a request to your Node server for http://server/file.html would serve /var/www/file.html.

router is code that runs your routes. When you do app.get('/user', function(req, res) { ... });, it is the router that actually invokes the callback function to process the request.

The order that you pass things to app.use determines the order in which each middleware is given the opportunity to process a request. For example, if you have a file called test.html in your static folder and a route:

app.get('/test.html', function(req, res) {
    res.send('Hello from route handler');
});

Which one gets sent to a client requesting http://server/test.html? Whichever middleware is given to use first.

If you do this:

app.use(express.static(__dirname + '/public'));
app.use(app.router);

Then the file on disk is served.

If you do it the other way,

app.use(app.router);
app.use(express.static(__dirname + '/public'));

Then the route handler gets the request, and "Hello from route handler" gets sent to the browser.

Usually, you want to put the router above the static middleware so that a accidentally-named file can't override one of your routes.

Note that if you don't explicitly use the router, it is implicitly added by Express at the point you define a route (which is why your routes still worked even though you commented out app.use(app.router)).


A commenter has brought up another point about the order of static and router that I hadn't addressed: the impact on your app's overall performance.

Another reason to use router above static is to optimize performance. If you put static first, then you'll hit the hard drive on every single request to see whether or not a file exists. In a quick test, I found that this overhead amounted to ~1ms on an unloaded server. (That number is much likely to be higher under load, where requests will compete for disk access.)

With router first, a request matching a route never has to hit the disk, saving precious milliseconds.

Of course, there are ways to mitigate static's overhead.

The best option is to put all of your static resources under a specific folder. (IE /static) You can then mount static to that path so that it only runs when the path starts with /static:

app.use('/static', express.static(__dirname + '/static'));

In this situation, you'd put this above router. This avoids processing other middleware/the router if a file is present, but to be honest, I doubt you'll gain that much.

You could also use staticCache, which caches static resources in-memory so that you don't have to hit the disk for commonly requested files. (Warning: staticCache will apparently be removed in the future.)

However, I don't think staticCache caches negative answers (when a file does not exist), so it doesn't help if you've put staticCache above router without mounting it to a path.

As with all questions about performance, measure and benchmark your real-world app (under load) to see where the bottlenecks really are.


Express 4

Express 4.0 removes app.router. All middleware (app.use) and routes (app.get et al) are now processed in precisely the order in which they are added.

In other words:

All routing methods will be added in the order in which they appear. You should not do app.use(app.router). This eliminates the most common issue with Express.

In other words, mixing app.use() and app[VERB]() will work exactly in the order in which they are called.

app.get('/', home);
app.use('/public', require('st')(process.cwd()));
app.get('/users', users.list);
app.post('/users', users.create);

Read more about changes in Express 4.