Order of routes when using parameters in ExpressJS

Order of routes when using parameters in ExpressJS

In ExpressJS there's a little gotcha to be aware of when we specify a routing order.

In ExpressJS there's a little gotcha to be aware of when we specify a routing order.

ExpressJS calculates the priority of a route based on the specificity of its path and the order by which they are declared. Routes are ordered from the most specific to the less specific one.

Suppose that we have the following routes:

'use strict';

const app = require('express')();

app.disable('x-powered-by');

app.get('/', (req, res) => {
   res.send('Home page');
});

app.get('/:post', (req, res) => {
   res.send('Single post');
});

app.get('/page', (req, res) => {
    res.send('A static page');
});

app.get('*', (req, res) => {
   res.send('Any');
});

app.listen(3000);

We know that the path * is the less specific so we correctly put this path to the end of the routes. However, the above code doesn't work as intended because a parametric path inserted just before a literal one takes the precedence over the literal one.

Then we need to refactor our code as follows:

'use strict';

const app = require('express')();

app.disable('x-powered-by');

app.get('/', (req, res) => {
   res.send('Home page');
});

app.get('/page', (req, res) => {
    res.send('A static page');
});

app.get('/:post', (req, res) => {
   res.send('Single post');
});

app.get('*', (req, res) => {
   res.send('Any');
});

app.listen(3000);

Bear in mind that in ExpressJS there's no built-in way to declare our routes as a list ordered by priority.