Search code examples
expressexpress-router

Is there a way to apply middlewares on all of specific request method?


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!


Solution

  • 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.