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.

Understanding functional middleware

Understanding functional middleware

There are two types of middleware in NestJS. One is the common middleware class, which uses the Nest middleware interface to define a middleware. Second one is a simple function working as a middleware, where we can define a middleware without implementing the nest middleware interface, that is by creating a function that is a middleware function. Let's see how we do that. Inside the middleware folder, I'll create a new file convert.middleware.ts. Now here, I will create a middleware function by giving export function convert middleware, is the name of middleware. And inside the argument, I'll give the request parameter of type request from express and response parameter of type response from express. And finally, the next parameter of type next function. So this is what a basic function middleware will contain as arguments. Let's define the middleware logic where we simply try to convert the request body into JSON. I will give an if condition. If request.body exists and type of…

Contents