Express routes - best way to make a url serve static and dynamic content


Suppose I have a urls like
... etc

where 'abc' and 'huyr' in this example are IDs, and i'd fetch info from the database where the key is that id.

But suppose I also want static links (that'll serve static pages) to follow the same url format:

What would be the best way to do this?

Right now I have something like this in mind

exports.view = function(req, res) {
    var id =
    switch (id) {
        case 'about':
            // load 'about' controller
        case 'contact':
            // load 'contact' controller
            // proceed with this function


Is this the best approach? is there a more efficient/organized way to do this?

Problem courtesy of: sqram


Best way, in my opinion, would be to serve those pages, static or not, like you would with any other page. Respond to the GET request with the right page.

// will respond to
app.get('/about', function( req, res, next ) {
    res.render('about.ejs'  // etc

// will respond to
app.get('/contact', function (req, res, next) {
    res.render('contact.ejs' // etc

// will respond to any first subdir (iirc)
app.get('/:id', function ( req, res, next ) {
    var id = req.param['id'];

    // db query, etc

You static pages of course can be in a route to make it cleaner. Only thing you need to make sure of is you respond to those static routes before the id route, or else you will be responding to the about/contact url with the route that you want responding to the ids. Order matters here.

Solution courtesy of: Chris


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.