req.params in middleware

req.params are not available anymore in the middleware. However it is still available in the router.

eg:

app.use(function(req, res, next){
    console.log(req.params.country); //not valid
        next();
});

app.get('/:country', function(req, res, next){
     console.log(req.params.country); // valid
     next();
});

Author: Fantashit

4 thoughts on “req.params in middleware

  1. @defunctzombie is it possible to read req.params if you associate it with a particular mount point ?
    ie.. please check my question here. http://stackoverflow.com/questions/25319731/cannot-get-request-params-in-express-middleware/25319790#25319790

    //middleware
    function userMiddleware(req, res, next) {
      console.log('user came in. Hello ' + req.param('name'));
      next();
    }
    
    //register middleware
    app.use('/user', userMiddleware)
    
    // routes
    app.get('/user/:name', function(req, res) {
      res.send('username : ' + req.params.name);
    });
  2. Sorry for bringing this up again. I wrote security middleware to check various things on incoming requests, one of those things is the params. It works when I put it with the route, but does not work at an ‘app.use’ level. Is there anyway possible that I can make this work without having to put it on each route? It would be so much cleaner to maintain this way.

  3. +1

    This would be very handy to have, but I get why it works the way it does for .use(). Perhaps .param() could accept a wildcard or regex for the name.

Comments are closed.