From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Controller-driven route middleware

Controller-driven route middleware

The for routes method in NestJS middleware allows you to specify which routes the middleware should apply to. But let's say when you want to achieve granular control, meaning you want to apply middleware for all the routes within a controller, then in such cases, we can use the controller based approach where we define the controller class inside the forRoutes method. So inside the forRoutes method, I'll remove the path and instead, we'll give the app controller class. This allows you to target the middleware on a specific set of routes defined within a single controller. This is how a controller driven route can be defined. And this provides more flexibility as you just define the controller class directly without having to figure out the specific route paths. Let's check the postman. We already have the path and content type set. I'll just make the request. And we get the content type returned as the route 2 is excluded. Let me change the route to route 3 and make the request. Now…

Contents