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.

Applying multiple middlewares

Applying multiple middlewares

In scenarios where middleware needs to manage multiple tasks, such as authentication and filtering, etc., it is advisable to divide the middleware into separate modules. By this way, the code becomes easier to manage and can be reused more easily. Also, this separates the different tasks. For example, one piece of middleware could just handle logins, while another deals with filtering data. This way, everything stays organized. So, let's see a simple example and understand how we can apply multiple middlewares. I will first create a middleware using the nest CLI, giving the command nest generate middleware slash middleware, folder I want to define the middleware in and the middleware name slash request details hyphen hyphen no spec as we do not want any test file. Let's open the file. I'll update the request and response type for the use method. Now what we are going to do here is we will keep it very simple. I'll first destructure the request method, URL, body, and headers from the…

Contents