Search code examples
node.jsexpressurl-routing

How to declare a mandatory parameter in node.js/express router


i got a series of routes like :

var router = express().Router;
router.get('/',middleware1,middleware2);
router.get('/courses',middleware1,middleware2,..)
router.post('/dates',middleware1,middleware2,..)

app.use('/u',router);

Now, when i declare the root of the route in

app.use('/u',router);

i would like to put a mandatory parameter that has to be present in every route of the micro-app like

app.use('/u/:user_name/',router);

So that i can check for every route with router.param the existence of this param in a db.

Is something like that possible by defining the param in the root of the micro app and not in every single route like

router.get('/:user_name/',middleware1,middleware2);
router.get('/:user_name/courses',middleware1,middleware2,..)
router.post('/:user_name/dates',middleware1,middleware2,..)

as they are actually a lot in the real application and it would be a pain to change them all?

Really thanks !


Solution

  • You should be able to do this using mergeParams so long as you're using a recent enough version of Express.

    var router = express.Router({mergeParams: true});
    

    Then this will work:

    app.use('/u/:user_name/', router);
    

    mergeParams is documented here:

    https://expressjs.com/en/4x/api.html#express.router