Home > Back-end >  Is there a way to apply middlewares on all of specific request method?
Is there a way to apply middlewares on all of specific request method?

Time:10-22

I have been working on a typescript project. I have created a middleware to check users' subscription and do not want to let users access PUT and POST routes. But I still want them to be able to access GET and DELETE requests. I know that the following line applies the checkSubscription middleware to all the requests on the route.

router.use(checkSubscription)

I only want the middleware to run if the request type is PUT or POST. I could do the following, of course

router.get("/endpoint1", controller1);
router.put("/endpoint2", checkSubscription, controller2);
router.post("/endpoint3", checkSubscription, controller3);
router.delete("/endpoint4", controller4);

Notice that the above PUT and POST requests run the checkSubscription middleware. But if I could declare on the top of the route file to run the middleware on all POST and PUT requests, that would save a lot of work and time.

Any kind of help would be highly appreciated. Thanks!

CodePudding user response:

You can restrict the middleware to PUT and POST requests by evaluating the req.method inside:

function checkSubscription(req, res, next) {
  if (req.method !== "PUT" && req.method !== "POST") return next();
  // Rest of your middleware code
}

This keeps the rule "this middleware is only for PUT and POST" local to the middleware, no matter how often it is referenced in other statements like router.use and router.post.

CodePudding user response:

But if I could declare on the top of the route file to run the middleware on all POST and PUT requests, that would save a lot of work and time.

You can just do something like this:

router.put("*", checkSubscription);
router.post("*", checkSubscription);

This will only call the checkSubscription() middleware for all PUT or POST requests that hit this router.

The "*" will match any path that goes through this router, but you could use any particular Express route pattern/regex there that you want if you want it to match more than one path, but not all paths.

As it sounds like you already know, you can also control route declaration ordering to give some routes a chance to handle the request before the middleware gets a shot to run.

CodePudding user response:

Since Express runs middleware (including route handlers) in order, you can place the routes for which you don't want to run the middleware first, then the middleware, then the routes for which it does need to run:

router.get(...);
router.delete(...);

router.use(checkSubscription);

router.post(...);
router.put(...);

It does require some diligence with regards to app maintenance, because developers need to understand that the order in which the handlers are declared is relevant.

  • Related