docksteaderluke
docksteaderluke

Reputation: 2265

Express v4: How do I run route-specific middleware before param middleware?

Long story short, I have a rather odd routing scenario where I need to invoke a middleware before the parameter middleware is invoked:

router.param('foo', function (req, res, next, param) {
  // Get the param value
  ...
  next()
})

router.route('/:foo')
  .all(function (req, res, next) {
    // I want to run this before the router.param middleware
    // but I don't want to run this on /:foo/bar
    ...
    next()
  })
  .get(function (req, res, next) {
    // Run this after the router.param middleware
    ...
    res.send('foo')
  })

router.route('/:foo/bar')
  .get(function (req, res, next) {
    // Run this after the router.param middleware
    ...
    res.send('bar')
  })

Now, I understand why the param middleware is typically run first, but is there a way around this?

I've tried to use router.use without a path like so:

router.use(function (req, res, next) {
  // I want to run this before the router.param middleware
  // but I don't want to run this on /:foo/bar
  ...
  next()
})

...and call it before the router.param middleware but then it would be invoked for /:foo/bar as well.

Finally, if I use router.use with a path like so:

router.use('/:foo', function (req, res, next) {
  // I want to run this before the router.param middleware
  // but I don't want to run this on /:foo/bar
  ...
  next()
})

...the router.param middleware gets called first (as you would expect).

Is there a way to do this?

Upvotes: 0

Views: 283

Answers (1)

Jordonias
Jordonias

Reputation: 5848

I'm by no means an expert at regular expressions, but you can use regular expressions to match routes. This would work for your specific use case, although there may be a better way of doing it.

router.use(/^\/[^\/]*$/, function(req, res, next) {

});

Upvotes: 1

Related Questions