Middlewares with Route definition or Routes with Middleware definition I am currently working on an Node based Express application. I have found Express's middlewares approach quite pleasing however, we all run in scenarios where a certain route or routes don't need a specific middleware.

I have found two approaches:


Adding middleware globally exempting the routes it doesn't need to run for. express-jwt is good example of this:

app.use(jwt().unless(
    '/someroute',
    '/someotherroute',
    ...
);

app.use(someothermiddleware().unless(
    '/someroute2',
    ...
);

app.use(someothermiddlewaretoo().unless(
    '/someroute3'
    ...
);

Adding middleware(s) to each route you define:

route.get(
   '/someroute1',
   [ jwt(), someothermiddleware, someothermiddlewaretoo ],
   function(req, res) {
       ...
   }
);

route.get(
   '/someroute2',
   [ jwt(), someothermiddlewaretoo ],
   function(req, res) {
       ...
   }
);

route.get(
   '/someroute3',
   [ jwt(), someothermiddleware ],
   function(req, res) {
       ...
   }
);



I can see that Approach #2 looks like some work however, I believe Approach #2 is way better in terms of a large application where you might have nested routers. You can be on any route and know exactly what middlewares it gets executed with.

With Approach #1, you get things up and running easily but, it will be pain to check if this route is being included for specific middleware every time you try to fix a bug.

Which approach is better in your opinion? Or, is there another approach that you would like to share?
I personally prefer Approach 2 since it will increase readability and you can easily find out which middle-ware are applied to a route rather than to go to each excepted middle-ware and calculate. That is a lot of work for future purpose.