1

I would like to have the following routes:

// Services without csrf()
router.get('/user/:uid', userRes.findUser, userRes.GETUser);
router.post('/user/:uid', userRes.findUser, userRes.POSTUser);

// Rest of routes, with csrf()
router.use(csrf());

router.post('/user/subscribe', indexRes.POSTSubscribe);

But what happens here is that POST /user/subscribe is matching second route.

I've been reading Express routes parameter conditions but it shows how to filter numbers. I would like to filter 'subscribe' path:

Is there any chance?

Community
  • 1
  • 1
Miquel
  • 8,339
  • 11
  • 59
  • 82

2 Answers2

1

If you move your /user/subscribe route before the /user/:uid route, it will get executed instead of the /user/:uid route for requests to /user/subscribe. Routes/middleware in Express are executed in the order they are attached.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • But what about csrf then? I'm placing in this order to disallow csrf checks to `/user/:uid` – Miquel Oct 16 '14 at 17:53
  • One solution for that might be something like: `router.post('/user/subscribe', csrf(), indexRes.POSTSubscribe);` Or just evaluate `csrf()` once and re-use that returned middleware in multiple places. – mscdex Oct 16 '14 at 17:56
  • Hmmm... I think it can be a little error prone (one could forget to put csrf middleware in the required routes) – Miquel Oct 16 '14 at 18:19
  • You can leave your `router.use(csrf);` where it is, which should still work for any other routes placed after the `/user/:uid` route. – mscdex Oct 16 '14 at 18:32
  • So maybe I'm not understanding your solution. The problem is that I need csrf to work with `subscribe` but not with `/user/:uid`. So If I place `/user/subscribe` before `/user/:uid` and leave `router.use(csrf)` after `/user/:uid`, I need to put csrf to `/user/subscribe`(which I think I can do some mistake in future as more `/user/xxx` should come) – Miquel Oct 16 '14 at 19:28
1

You could use router.param:

var staticUserPaths = ['subscribe'];
router.param('uid', function (req, res, next, id) {
  if (~staticUserPaths.indexOf(id)) {
    next('route');
  } else {
    next();
  }
});
David
  • 2,741
  • 16
  • 26